Getting form data from html form using flask and p

2019-09-17 16:23发布

问题:

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

<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:

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