Accessing Request (GET) Data in Flask
Subject: Flask: Python Web Development
To access parameters submitted in the URL (? variable=value) or a form with get method (method="GET") you can use the args attribute. Example request.args.get('variable')
Data in URL
Normally a user will not enter a data to a URL like this tealearn.org/page?id=1 OR tealearn.org?name=Ben however you must have noticed that some times will browser a website the URL sometimes takes this form.
What this means is that a link you must clicked makes data (page?id=1) to be pass from one page to another for a dynamic content generation.
In
page?id=1 the data (1) is sent to via the variable (id) to URL (page)
Example 1
In this example we created an HTML file "items.html" in the templates folder. With the content:
Students Record
Students Record
Notice that we manually created the links (detail?studentid=1) to send number or value through studentid to detail URL (This can be created automatically by looping through a record in a database).
When you submit a data via a URL (Query string) you use the GET request to collect it. Let us update the Python app.py file with the following code segment.
from flask import Flask, render_template, request
# this block will render the student list page
@app.route('/students')
def students():
return render_template('items.html')
# display detail using the collected value
@app.route('/detail', methods=['GET', 'POST'])
def method():
if request.method == 'GET':
#the request get that collects the data
student_id = request.args.get('studentid')
if student_id=="1":
student_name="Ben"
if student_id=="2":
student_name="Abu"
if student_id=="3":
student_name="Abiodun"
return render_template('detail.html', stuid=student_id, stuname=student_name)
if __name__ == '__main__':
app.run(debug=True)
The detail.html that will display the result or student detail should have this context.
Students Record
Students Record
{% if stuid %}
Student id: {{ stuid }}
Student name: {{ stuname }}
{% else %}
Record not found!
{% endif %}
Submit data using FORM and GET method
Here is another version of the items.html, we called this
items_form.html ensure its in the templates folder as usual.
Example 2
Students Record
Students Record
This form will do exactly same thing as the listed linked students page in items.html by appending it's data to the URL as usual, this is because GET method was used