Python-Flask/C2/Request-Response-Cycle-in-a-Flask-Web-App/English

From Script | Spoken-Tutorial
Revision as of 17:59, 26 December 2018 by SiddharthaSarkar (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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
  • About the request-response cycle in Flask.
  • Different attributes of the request object.
  • Different types of request data.
  • Several HTTP response codes.


Slides 3: System Requirements To record this tutorial, I’m using
  • Ubuntu Linux 16.04 OS
  • Python 3.5.2
  • Atom text editor 1.22.1 and
  • Firefox web browser


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
  • Linux commands
  • Python programming and
  • HTML syntax

If not, then please go through the corresponding tutorials on this website. http://spoken-tutorial.org

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
  • Query arguments sent as part of the URL in the browser.
  • Form data collected from web forms.


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.


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]

Type

http://localhost:5000/

And press Enter.

Next, 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 here.


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 framework value 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 that we 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]


Type http://127.0.0.1:5000/query?framework=my_flask

In the address bar, next to the word query type:


Question mark framework <equal to> my underscore 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.

Before the if statement, 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')

Now inside this form route, define a view function my_form()


Once again, type the code as shown here.

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


  • the client will send data to the server using the form.
  • This is to update the server with some information


Slide 9: POST method *
For example - you enter your username and password while logging in to a website.
  • In contrast, GET request method is used to get or read some data from the server.


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.

[Text Editor] Switch back to the editor.
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 the following piece of code.


This code will display the values of firstname and 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 the if condition, type the following 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]


Type http://127.0.0.1:5000/form


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 retrieved the firstname and lastname from the request object.


So this shows how the form attribute of the request object is used.
[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 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]


Type http://localhost:5000/user/Sid


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 received 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 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,


  • The request-response cycle in Flask.
  • Different attributes of the request object.
  • Different types of request data.
  • Several HTTP response codes.


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.

Contributors and Content Editors

Pravin1389, SiddharthaSarkar