Python-Flask/C2/First-Flask-Web-App/English

From Script | Spoken-Tutorial
Revision as of 17:07, 21 January 2019 by SiddharthaSarkar (Talk | contribs)

Jump to: navigation, search

Title of script: First Flask web application

Author: Siddhartha Sarkar

Keywords: ​Video tutorial, Python Flask, Hello World, Routes, View Functions, HTTP protocol.


Visual Cue Narration
Slide 1: First Flask web app Welcome to the spoken tutorial on the first Flask web application.
Slide 2: Learning Objectives In this tutorial, we will learn
  • To write and analyze our first Flask application.
  • The concept of Routes and View functions.
  • About Dynamic content served by dynamic URLs.


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 on
  • Linux commands and
  • Basic Python programming


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

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.


(dot) refers to the present working directory.

[Terminal]

Highlight (flask_venv)

Notice that we are now inside the virtual environment flask_venv.
Only narration Open the file hello_flask.py in a text editor.


I will be using the atom text editor but you can use your prefered text editor.

[Terminal]


$ atom hello_flask.py

I will type the command.

atom<space> hello underscore flask dot py


and press Enter.



Now let us understand what the code does, line by line.

[Text Editor]

Highlight

“from flask import Flask”

The first line is from flask import Flask.


It simply says import Flask module from flask folder.

[Text Editor]

Point to the left pane of Atom.


Collapse flask_venv->lib->python3.5->site-packages

And hover over flask foder.

Look at the directory structure If we use atom editor, we can see the folder structure in the left pane. Else we have to show in the file browser. As we will be using atom editor throughout this series, we don't need to switch to the file browser.+pravin1389@gmail.com

Can you pls confirm what Siddharth is saying?We are using Atom throughout the course. If they use other editors they will see the same phenomenon in the respective directory where flask gets installed.

We expect that they will use Atom.This is a problem if learners are using other text editors like gedit, nano, etc.at the left pane of the Atom text editor window.


Observe that there is no flask folder in the project.


So how does the compiler find and import the Flask module?


Python is set to look for modules in the site-packages.

Highlight


app = Flask(__name__)

In the second line, we have created an object for the flask class.


This object of the Flask class is our WSGI application.


WSGI stands for Web Server Gateway Interface.


We will come to what WSGI is later.


This takes an argument double underscore name double underscore.


This argument basically refers to the name of the file.


In our case it is “hello_flask”.


Flask uses this argument to determine the root path of the application.

[Text Editor]


Highlight

@app.route('/')

In the next line, the route function of the Flask class is a decorator.


It tells the application, which URL should call the associated function.


In this case, root slash is the URL.


It refers to home or top domain.

[Text Editor]


Highlight

@app.route('/')

Decorators are a standard feature of the Python language.


They can modify the behavior of a function in different ways.


In our case, it is used to associate a function with a URL.


To know more about decorators you may refer to the Python Spoken Tutorial series.

Slide 5: Routes (img 1) Let us understand the concept of routes in detail now.


Look at this diagram.


This shows a simplified client and server diagram.

Slide 6: Routes (img 2)


The client sends a request to the web server.


In our case, the web browser is the client.

Slide 7: Routes (img 3) Then the web server has to process the request and generate a response.


And the Flask application instance does this job.


The web server sends the request to the Flask application instance.

Slide 8: Routes (img 4) On receiving the request the app matches it with the available route patterns.


Slide 9: Routes
  • Thus the application instance knows which function to execute for which URL.
  • This happens because it keeps a mapping of the URLs to functions.
  • Here we need the concept of routes.


Slide 9: Routes
  • The association between a URL and the function that handles it, is called a route.
  • The Flask app executes the associated function and returns a response.


Slide 9: Routes
  • Routes can be either static or dynamic.
  • In the present case, we have a static route.



We will discuss dynamic routes in a moment.

[Text Editor]


Highlight

def hello_world():

Let’s come back to our “hello world” app.


In the next line, we define the associated function for this route.


This function gets executed when the root URL is hit.


In our case the root URL is http://127.0.0.1:5000


Here, we have named the function as “hello_world”.


However, you may choose any other name of your choice.


This function associated with a route is called ‘view function’.

[Text Editor]


Highlight

return 'Hello, World!'

The next line says return 'Hello, World!'


So this view function simply returns a string “Hello World”.

[Text Editor]


Type


if __name__ == '__main__':(Tab) app.run()

Now let us add a few more lines of code at the end.


Line 8 and 9.

[Text Editor]


Highlight


if __name__ == '__main__':(Tab) app.run()

This is a customary common practice.


This ensures that server is launched only if the script runs directly from the terminal.


Otherwise app dot run is skipped.


It may happen that a script is being called from another script.


In that case the imported script should not start a new server.


Hence we follow this practice.

Ctrl+S Let us save the file by pressing Ctrl and S keys.
[Terminal]

Type


$ export FLASK_APP=hello_flask.py

Now back in the terminal and run the hello world app.


Type export <space> FLASK_APP <equal to > hello underscore flask dot py


Press Enter.

[Terminal]

Type


$ python3 -m flask run

Now type


python3 <space> hyphen m <space> flask <space> run


And press Enter.


We can see a message “Running on http://127.0.0.1:5000/


Here, 127.0.0.1 is the IP address for the localhost.


Flask app is running in the local host on port 5000.

[Firefox]


Type

http://127.0.0.1:5000/

And press Enter.

Now, open any web browser.


In the address bar, type http://127.0.0.1:5000/ and press Enter.

[Firefox]

Highlight ‘Hello, World!’

We can see the message ‘Hello, World!’ written in the browser window.
Switch back to the terminal.


Stop the server by pressing Ctrl and C keys together.

[Terminal]


atom hello_flask.py

Now we will write code for a dynamic route and also define a view function called hello_user.


Switch to the editor window.

Type


@app.route('/user/<username>')

def hello_user(username):

(Tab) return '<h1>Hello, %s!</h1>' % username

Before the if condition, type the code as shown here.


Highlight


@app.route('/user/<username>')


This route has a URL, home/user/<username>


where home is the root domain URL of the server.


whereas, username is a variable.


We will use this variable in the view function to change the content in the browser.

Highlight


def hello_user(username):

(Tab) return '<h1>Hello, %s!</h1>' % username

This function will simply return a string ‘Hello’ username.


Note that the output in the browser will vary as per the username in the URL.


h1 is the level one heading tag of HTML.

Let us save the file by pressing Ctrl and S keys


Switch back to the terminal.

[Terminal]

$ python3 -m flask run [Enter]

Run the app by executing the following command.


[Firefox]


Type

http://127.0.0.1:5000/user/Sid

[Enter]

Switch to the web browser.


In the address bar, type http://127.0.0.1:5000/user/Sid


and press Enter.

[Firefox]


Type

http://127.0.0.1:5000/user/Tom

[Enter]

We got the output as “Hello Sid!”.


Now let’s try Tom instead of Sid

In the address bar, replace Sid with Tom.


Press Enter.


The output has changed to ‘Hello Tom!’


We have a dynamic URL in play here.

Slide 10: Example URL This is what you may have observed in facebook as well.


Facebook individual users have a URL of the type:

www.facebook.com/profile_id


Here profile_id refers to the unique ID of a facebook user.


Depending on the unique ID, facebook server fetches the individual profile pages.Switch to the browser window.

[Firefox]


Type

http://127.0.0.1:5000/posts

[Enter]

Let’s try a URL for which we did not define a route.


Switch to the browser window.


Replace /user/tom with posts and press Enter.


Observe that we got Not found message.

[Terminal]


Highlight 404.


Highlight 200’s.

Switch to the terminal.


Observe that, the server has returned a 404 response code.


This error code indicates that the web page requested for, does not exist.


Whereas most previous response codes were 200.


We will discuss in detail these HTTP responses in the upcoming tutorials.

Press Ctrl+c simultaneously To stop the server, press Ctrl and C keys simultaneously.
[Terminal]


Type deactivate and press Enter

We will deactivate the Virtual Environment.


Type deactivate and press Enter.

This brings us to the end of this tutorial.


Let us summarise

Slide 10: Summary In this tutorial, we learnt about


  • The working of our first Flask application.
  • The concepts of routes and the view functions.
  • Running a Flask app in a Web browser.
  • Dynamic content served by dynamic URLs.


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 13:

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

Nancyvarkey, Pravin1389, SiddharthaSarkar