python接收表单_使用flask和python从html表单获取表单数据

I am trying to get the form data out of the text fields when the submit is pressed so I can put it into json format and access the json data as another page which would be localhost:5000/info. Every time I try to access the data with request.form.get('') it only returns an empty dictionary. I read the other posts on stackoverflow trying to figure out the problem but none of the solutions seem to work. If possible I would like to avoid having to use templates or modules other than flask.

This is my python code

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()

This is the HTML

Intersection 1

East Light

West Light

North Light

South Light

解决方案

I tried your code and it works for me.

I only had to add global in cars() to get results on page /info.json

def cars():

global numCarsEast, numCarsWest, numCarsSouth, numCarsNorth

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值