Accessing Request (POST) Data in Flask
Subject: Flask: Python Web Development
For web applications it’s crucial to react to the data a client sends to the server.
This data is often submitted through web or HTML form, for example Feedback Form, Registration/Login Form and Order Form.
In Flask this information is provided by the request object. So we have to import it from the flask module first:
from flask import request
And use it's method attribute to access client data (data transmitted in a POST or GET request).
Step 1.
Create an HTML file in the templates folder named "order.html" and have this HTML code in it.
Notice, that the page is primarily a form that use the POST method to submit data to the "process" view or route.
Order Form
Complete the order form
Step 2.
Update your python file (app.py file), to include the
request object imported from flask.
from flask import request
Instead of individually having this object, with the Flask and render_template on separate lines, we can simple import all three with one line as we have we in the code below:
# import the three classes from flask
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/order')
def order():
return render_template('order.html')
@app.route('/process/', methods=['POST'])
def process():
if request.method == 'POST':
#collect the data using the form element name
yourname = request.form['yourname']
youraddress = request.form['youraddress']
phone = request.form['phone']
product = request.form['product']
qty = request.form['qty']
#calculate the total cost of order
if product == "Garri":
price = 500
elif product == "Fufu":
price = 100
elif product == "Akara":
price = 700
total_cost=price * int(qty)
msg = (f"You ordered for {qty} {product} and each cost {price}. Therefore the total cost {total_cost}. Thank you")
return render_template('process.html', name=yourname, message=msg)
if __name__ == '__main__':
app.run(debug=True)
Step 3.
Now create the "process.html" file in the "templates" folder, it will display the message after the process has completed.
Order Process
Order Process
{{name}} Thank you for your order
Orde detail:
{{message}}
Step 4.
Run the python program app.py and go the web browser to access the Order form using this URL.
http://localhost:5000/order
OR http://127.0.0.1:5000/order
Complete and submit the form.
See the attached screenshots for a sample completed and submitted.
Updated app structure
http://127.0.0.1:5000/order
Process output
By:
Benjamin Onuorah
Login to comment or ask question on this topic
Previous Topic Next Topic