使用Flask和Python获取HTML表单数据

0 投票
1 回答
3165 浏览
提问于 2025-04-18 10:44

我想在点击提交按钮时,从文本框中获取表单数据,然后把这些数据转换成json格式,方便在另一个页面访问这些json数据,那个页面的地址是 localhost:5000/info。可是每次我用 request.form.get('<id>') 来获取数据时,它总是返回一个空的字典。我在StackOverflow上看了其他帖子,想找出问题所在,但没有一个解决方案能奏效。如果可以的话,我希望能避免使用除了flask以外的模板或模块。

这是我的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>

1 个回答

0

我试了你的代码,结果对我来说是有效的。

我只需要在 cars() 里加上 global,就能在页面 /info.json 上看到结果了。

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

撰写回答