Python-Flask/C2/Request-Response-Cycle-in-a-Flask-Web-App/English
Title of script: The Request-Response Cycle in a Flask web app
Author: Siddhartha Sarkar
Keywords: Video tutorial, Python Flask, view functions, request object, HTTP response, debugging.
Visual Cue | Narration |
Slide 1: The Request-Response Cycle in a Flask web app | Welcome to the Spoken Tutorial on the request-response cycle in a Flask web app. |
Slide 2: Learning Objectives | In this tutorial, we will learn
|
Slides 3: System Requirements | To record this tutorial, I’m using
You can use any text editor and web browser of your choice. |
Slide 5: Pre-requisites | To follow this tutorial, you should have working knowledge of
If not, then please go through the corresponding tutorials on this website. |
Slide 6: The request object | We already said that the Flask app instance has to process the received request.
For processing, the app instance needs to have access to certain information. |
Slide 6: The request object | A few objects are provided to the view functions, where the processing takes place.
One of these objects is the request object. This object encapsulates the contents of the HTTP request sent by the client. |
Slide 7: The request object | The incoming request data can be of several forms. For example
We will discuss them in detail in this tutorial. |
Open a Terminal window | Let us open the Terminal by pressing Ctrl, Alt and T keys simultaneously on the keyboard. |
[Terminal]
Type cd project_flask & Press Enter |
Now go to the folder project underscore flask which we created earlier using cd command. |
[Terminal]
$ . flask_venv/bin/activate [Enter] |
Let us activate our virtualenv.
Type the command Dot space flask_venv slash bin slash activate And press Enter. |
[Terminal]
Highlight (flask_venv) |
Notice that we are now inside the virtual environment flask_venv. |
[Terminal]
Type $ atom hello_flask.py |
Let’s open the hello_flask.py file in a text editor, which we created earlier in this series.. |
[Text Editor]
Type “, request” |
Let’s look at how the request object is made available in a view function.
We will import the request object from the flask library. In the line from flask import Flask, we will add comma space request |
[Text editor]
Type in hello_world(): (As the first line) print("Request method is " + request.method) |
The request object has many attributes.
Let us access request inside the hello_world view function. Next to the function definition, type the code as shown. |
Highlight
print("Request method is " + request.method) |
This will print the method attribute of the request object. |
Press Ctrl+S | Save the file. |
[Terminal]
Type $ export FLASK_APP=hello_flask.py |
Let us start the server to see the changes.
Switch to the terminal. Type export <space> FLASK_APP <equal to> hello underscore flask dot py And press Enter. |
[Terminal]
Type $ python3 -m flask run [Enter] |
Now type
python3 <space> hyphen m <space> flask <space> run And press Enter. |
[Firefox]
And press Enter. |
Now, open a web browser.
In the address bar, type http://localhost:5000 and press Enter. |
Highlight the output | We got the output as Hello World. |
[Terminal] | Switch to the terminal once again. |
Highlight “Request method is Get” | Observe that the current request method is “GET”.
The request object is indeed accessible inside the view functions. The GET HTTP method is used to retrieve data from the web server. It specifies the parameters in the URL of the request itself. |
Only narration. | Now let us see how one can send data to the server using the request object.
There are a number of ways to do this. The simplest one is via Query Arguments. |
[Text Editor]
Type @app.route('/query') def query_args(): (Tab)framework = request.args['framework'] (Tab)return '''<h1>The framework value is: {}</h1>'''.format(framework) |
Let us define a new route to explain this.
Switch back to the editor. Before the if condition, type the code as shown here. We will call it as query. |
Press Ctrl+S | Save the file. |
Highlight
<h1>The framework value is: {}</h1> |
Here we have written the statement inside the HTML’s h1 heading tag. |
Highlight args in
framework = request.args['framework'] |
Here we have an attribute called args in the request object.
This is a dictionary object. It has the parsed contents of the query string in the URL. We will use this attribute to retrieve the data sent as query arguments. |
[Terminal] | Switch to the terminal. |
Press Ctrl+C | Press Ctrl and C keys to stop the server. |
Type
$ python3 -m flask run [Enter] |
Press the up arrow key to get the command to run the flask application.
And press Enter. |
[Firefox] | Switch to the web browser. |
Type http://localhost:5000/query
And press Enter. |
In the address bar, next to 5000 type slash query
and press Enter. |
Highlight the error | We get a “Bad request” error. |
[Terminal] | Switch back to the terminal. |
Highlight
"GET /query HTTP/1.1" 400 - |
Notice that this response has HTTP code 400.
This is one of the common errors you will encounter while developing Flask applications. 400 code indicates that the server could not understand the request due to invalid syntax. |
Only narration. | So now we have to find out where this syntax issue has occurred.
We will scan the code to spot the error. This is called debugging. |
[Text Editor]
Press Ctrl+C |
For this, we have to start the server in the debug mode.
Before that, we need to stop the current server by pressing Ctrl and C keys together. |
[Terminal]
Type $ export FLASK_ENV=development |
Then type export <space> FLASK <underscore> ENV <equal to> development
and press Enter. |
[Terminal]
Type $ python3 -m flask run |
Now type
python3 <space> (hyphen)m <space> flask <space> run And press Enter. |
[Terminal]
Highlight Debug mode: on |
Observe that now it says debug mode is on. |
[Firefox]
Click on the refresh button. |
Go back to the browser and refresh the page.
Since the debug mode is active, we have received a traceback of errors. This means that we get the line numbers where the errors have occurred in different files. |
Highlight the different error lines in the traceback of errors. | The traceback includes the errors from the corresponding flask files as well.
This is because an error in one file causes errors in other files as well. This is termed as the cascading effect. We have to look for the error in a file that we have written. |
Highlight
framework = request.args['framework'] |
Scroll down and search for the error in the file hello_flask.py |
Highlight
BadRequestKeyError |
We have a BadRequestKeyError.
That means that the key “framework” for the dictionary request.args does not exist. To rectify this, we have to modify that line. |
[Text editor]
Type framework = request.args.get('framework') |
Switch to the editor.
Now change the line as shown. |
Press Ctrl+S | Save the file. |
[Text Editor]
Highlight framework = request.args.get('framework') |
Now even if the key is not found, python will handle this properly.
That means, instead of causing a 400 error, it will return None. |
[Terminal] | Switch to the terminal. |
Press Ctrl+C | Once again stop the server by pressing Ctrl and C keys together. |
Type python3 -m flask run | Then run the server again. |
[Firefox] | Go back to the browser and refresh the page. |
Click on the refresh button. | Now we have the output as expected.
The framework value is None. |
Next, we will send some value for the framework via the URL. | |
[Firefox]
Click on the address bar |
args gets the part of the URL after the question mark in the form of a python dictionary. |
[Firefox] | In the address bar, next to the word query type:
Question mark framework <equal to> my_flask And press Enter. |
Highlight:
The framework value is: my_flask |
So now we have the framework attribute of the dictionary set to my_flask.
We got the result as expected. |
Slide 8: form attribute | The request object has one more important attribute called ‘form’.
It can be used to collect data from the user using a web form. And then store the data as a dictionary in the form attribute. Let us look at an example. |
[Text Editor]
Type @app.route('/form', methods=['GET', 'POST']) |
We will see how form data can be sent and received using the request object.
Let us define a new route called form. We allow both GET and POST as possible request methods. Type the code as shown here. |
[Text Editor]
Type def my_form(): if request.method == 'POST': firstname = request.form.get('firstname') lastname = request.form.get('lastname') |
Inside the form route, define a view function my_form() |
Highlight:
if request.method == 'POST': firstname = request.form.get('firstname') lastname = request.form.get('lastname') |
This block will get executed, if the request is via POST method. |
Slide 9: POST method | In POST request method
|
Slide 9: POST method |
|
Only narration | Now let us store the form values into some variables.
We will obtain the entered values from the request object using the form attribute. |
Type
html_string1 = '''<h1>The firstname value is: {}</h1> <h1>The lastname value is: {}</h1>'''.format(firstname, lastname) return html_string1 |
Inside the if condition which checks the post method, type this code.
This code will display the firstname as well as the lastname. |
[Text Editor]
Type html_string2 = <form method="POST"> Firstname: <input type="text" name="firstname"> Lastname: <input type="text" name="lastname"> <input type="submit" value="Submit"> </form> return html_string2 |
Now outside this if condition, we type this code.
This will simply display a web form in the output, if the request method is GET. |
Press Ctrl + S | Save the file. |
[Terminal] | Switch back to the terminal. |
Press Ctrl+C | Stop the server by pressing Ctrl and C keys together. |
Type python3 -m flask run | Then run the server again. |
[Firefox] | Switch to the browser.
In the address bar type the URL as http://localhost:5000/form and press Enter. |
The page is displayed with a form. | |
Let us enter some values in the form. | |
Type First name as Spoken.
Last name as Tutorial |
I will type the First name as Spoken.
Last name as Tutorial. And then click on Submit button located at the bottom of the web form. |
[Firefox]
Highlight The text in the browser |
Here we have received the firstname and lastname from the request object. |
[Text Editor] | The last thing I want to talk in this section is about “500: Internal Server Error”.
This is one of the most frequent errors you will encounter during flask app development. |
Let us write a code snippet to demonstrate this. | |
[Text Editor] | Switch back to the editor. |
Type inside user(name):
a = 10/0 |
In the user view function, before the return statement type
a <equal to> 10 slash zero As we are dividing 10 by zero, we should get an error. Save the file. |
[Terminal] | Switch to the terminal. |
Press Ctrl+C | Stop the server by pressing Ctrl and C keys together. |
Type python3 -m flask run | Now run the server again. |
[Firefox] | Switch to the browser.
In the address bar type the URL as http://localhost:5000/user/Sid and press Enter |
[Firefox] | Observe that we have a ZeroDivisionError. |
Highlight star | Let’s switch to the terminal to see the HTTP status code. |
[Terminal]
Highlight "GET /user/error HTTP/1.1" 500 |
Here we can see HTTP response code as 500.
Which means we have encountered an internal server error. The 500 error simply implies that, there’s something wrong in the web server. |
Since we have the debug mode on, we know the specific reason for the error. | |
With this we come to the end of this tutorial.
Let us summarise. | |
Slide 10: Summary | In this tutorial, we learnt about,
|
Slide: About Spoken Tutorial project | The video at the following link summarises the Spoken Tutorial project.
Please download and watch it. |
Slide: Spoken Tutorial workshops | The 'Spoken Tutorial Project team conducts workshops and gives certificates.
For more details, please write to us. |
Slide: Forum for specific questions: | Please post your timed queries in this forum. |
Slide: Acknowledgement | Spoken Tutorial Project is funded by NMEICT, MHRD, Government of India.
More information on this mission is available at this link. |
This is Siddhartha Sarkar signing off.
Thanks for watching. |