Wednesday, 15 June 2011

Getting form data from html form using flask and python -



Getting form data from html form using flask and python -

i trying form info out of text fields when submit pressed can set json format , access json info page localhost:5000/info. every time seek access info request.form.get('<id>') returns empty dictionary. read other posts on stackoverflow trying figure out problem none of solutions seem work. if possible avoid having utilize templates or modules other flask.

this 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 homecoming 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') homecoming 'done' homecoming open('./carform.html').read() if __name__ == '__main__': app.debug = true app.run()

this html

<body> <form method='post'> <h2> intersection 1 </h2> <label> east lite </label> <input type=text id='eastlightint1' name='eastlightint1' /> <label> west lite </label> <input type=text id='westlightint1' name='westlightint1' /> <br /> <label> north lite </label> <input type=text id='northlightint1' name='northlightint1' /> <label> south lite </label> <input type=text id='southlightint1' name='southlightint1' /> <br /> <input type=submit value=submit> </form> </body>

i tried code , works me.

i had add together global in cars() results on page /info.json

def cars(): global numcarseast, numcarswest, numcarssouth, numcarsnorth

python html forms http flask

No comments:

Post a Comment