0
我試圖從按鈕提交時的文本字段中獲取表單數據,所以我可以把它放入json格式並作爲另一個頁面訪問json數據localhost:5000/info
。每次嘗試使用request.form.get('<id>')
訪問數據時,它只會返回一個空字典。我閱讀了stackoverflow上的其他帖子試圖找出問題,但沒有解決方案似乎工作。如果可能的話,我想避免使用燒瓶以外的模板或模塊。使用燒瓶和python從html窗體獲取表單數據
這是我的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>
切出約90%的代碼,我們不需要它 –
@PatrickCollins我厭倦了做這方面的一個簡化版本與一個聯繫信息頁面,只需要一個名稱和電子郵件,並有一個路由處理程序,但由於某種原因,該網頁按預期工作。這就是我發佈一切的原因。我想我可能會錯過一些小的東西,但是當我看到代碼時,我無法弄清楚問題所在。謝謝。 – alphamonkey