2014-06-23 66 views
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> 
+0

切出约90%的代码,我们不需要它 –

+0

@PatrickCollins我厌倦了做这方面的一个简化版本与一个联系信息页面,只需要一个名称和电子邮件,并有一个路由处理程序,但由于某种原因,该网页按预期工作。这就是我发布一切的原因。我想我可能会错过一些小的东西,但是当我看到代码时,我无法弄清楚问题所在。谢谢。 – alphamonkey

回答

0

我想你的代码,它为我工作。

我只有在cars()添加global得到网页上的结果/info.json

def cars(): 
    global numCarsEast, numCarsWest, numCarsSouth, numCarsNorth 
+0

它现在与全球谢谢你。 – alphamonkey