【问题标题】:Getting form data from html form using flask and python使用flask和python从html表单获取表单数据
【发布时间】:2014-08-13 04:24:56
【问题描述】:

我试图在按下提交时从文本字段中获取表单数据,以便我可以将其转换为 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>

【问题讨论】:

  • 删掉大约 90% 的代码,我们不需要它
  • @PatrickCollins 我厌倦了使用联系信息页面制作一个简化版本,该页面只包含姓名和电子邮件,并且有一个路由处理程序,但由于某种原因该页面按预期工作。这就是我发布所有内容的原因。我想我可能只是遗漏了一些小东西,但是当我查看代码时,我无法弄清楚问题是什么。谢谢。

标签: python html forms http flask


【解决方案1】:

我试过你的代码,它对我有用。

我只需在cars() 中添加global 即可在页面/info.json 上获得结果

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

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2020-04-11
    • 2016-05-28
    • 2017-07-22
    • 2014-11-18
    • 2018-01-17
    相关资源
    最近更新 更多