我正在尝试在按下提交时从文本字段中获取表单数据,因此我可以将其放入json格式并将json数据作为另一个页面访问localhost:5000/info
。每次我尝试使用request.form.get('<id>')
访问数据时,它只返回一个空字典。我读了stackoverflow上的其他帖子试图找出问题,但没有一个解决方案似乎工作。如果可能的话,我希望避免使用烧瓶以外的模板或模块。
这是我的python代码
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()
这是HTML
<body>
<form method='POST'>
<H2>
Intersection 1
</h2>
<label>
East Light
</label>
<input type=text id='eastLightInt1' name='eastLightInt1' />
<label>
West Light
</label>
<input type=text id='westLightInt1' name='westLightInt1' />
<br />
<label>
North Light
</label>
<input type=text id='northLightInt1' name='northLightInt1' />
<label>
South Light
</label>
<input type=text id='southLightInt1' name='southLightInt1' />
<br />
<input type=submit value=Submit>
</form>
</body>
答案 0 :(得分:0)
我尝试了你的代码,它对我有用。
我只需在global
中添加cars()
即可在页面/info.json
上获得结果
def cars():
global numCarsEast, numCarsWest, numCarsSouth, numCarsNorth