I am trying to get the form data out of the text fields when the submit is pressed so I can put it into json format and access the json data as another page which would be localhost:5000/info. Every time I try to access the data with request.form.get('') it only returns an empty dictionary. I read the other posts on stackoverflow trying to figure out the problem but none of the solutions seem to work. If possible I would like to avoid having to use templates or modules other than flask.
This is my python code
from flask import Flask, request, jsonify, redirect
app = Flask(__name__)
numCarsEast = None
numCarsWest = None
numCarsSouth = None
numCarsNorth = None
@app.route('/info.json', methods=['GET', 'POST'])
def getInfo():
if request.method == 'GET':
lightEast = {}
lightWest = {}
lightNorth = {}
lightSouth = {}
intersection1 = {}
lightEast['cars'] = numCarsEast
lightWest['cars'] = numCarsWest
lightNorth['cars'] = numCarsNorth
lightSouth['cars'] = numCarsSouth
intersection1['eastLight'] = lightEast
intersection1['westLight'] = lightWest
intersection1['northLight'] = lightNorth
intersection1['southLight'] = lightSouth
return jsonify(intersection=intersection1)
@app.route('/cars', methods=['GET', 'POST'])
def cars():
if request.method == 'POST':
numCarsEast = request.form.get('eastLightInt1', None)
numCarsWest = request.form.get('westLightInt1', None)
numCarsNorth = request.form.get('northLightInt1', None)
numCarsSouth = request.form.get('southLightInt1', None)
print(str(numCarsEast) + ' east')
print(str(numCarsWest) + ' west')
print(str(numCarsNorth) + ' north')
print(str(numCarsSouth) + ' south')
return 'done'
return open('./carForm.html').read()
if __name__ == '__main__':
app.debug = True
app.run()
This is the HTML
Intersection 1
East Light
West Light
North Light
South Light
解决方案
I tried your code and it works for me.
I only had to add global in cars() to get results on page /info.json
def cars():
global numCarsEast, numCarsWest, numCarsSouth, numCarsNorth