0% found this document useful (0 votes)
2 views45 pages

Chapter 5 Python Web Framework

The document provides a comprehensive guide on using the Flask web framework, including installation steps, environment setup, and creating a basic Flask application. It explains the importance of WSGI for communication between web servers and Python applications, as well as the Jinja2 templating engine for rendering HTML. Additionally, it covers routing, URL building with the url_for() function, and the flexibility and scalability benefits of using WSGI.

Uploaded by

nensighori18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views45 pages

Chapter 5 Python Web Framework

The document provides a comprehensive guide on using the Flask web framework, including installation steps, environment setup, and creating a basic Flask application. It explains the importance of WSGI for communication between web servers and Python applications, as well as the Jinja2 templating engine for rendering HTML. Additionally, it covers routing, URL building with the url_for() function, and the flexibility and scalability benefits of using WSGI.

Uploaded by

nensighori18
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

504 – Web Services and Framework (TYBCA Sem-V)

Unit – 5 Python Web Framework: Flask


Flask is one of the most popular web application frameworks written in
Python. It is a micro-framework designed for an easy and quick start. Extending with
tools and libraries adds more functionality to Flask for more complex projects. For
installation of Flask one must have already installed Python 2.7 or 3.5 and newer.
5.1 Installation of Flask and Environment Setup
Step 1: Install Virtual Environment
Install Flask in a virtual environment to avoid problems with conflicting
libraries. Check Python version before starting:
 Python 3 comes with a virtual environment module called venv preinstalled. If
you have Python 3 installed, skip to Step 2.
 Python 2 users must have to install the virtualenv module. If you have Python
2, follow the instructions given below for windows.
Install virtualenv on Windows
 1. Open the command line with administrator privileges.
 2. Use pip to install virtualenv on Windows:
py -2 -m pip install virtualenv
hint: https://phoenixnap.com/kb/install-pip-windows
Step 2: Create an Environment
1. Make a separate directory for your project:
mkdir <project name>
2. Move into the directory:
cd <project name>
3. Within the directory, create the virtual environment for Flask. When you create the
environment, a new folder appears in your project directory with the environment’s
name.
Create an Environment in Windows
 For Python 3:
Create and name a virtual environment in Python 3 with:
py -m venv <name of environment>
 For Python 2:
For Python 2, create the virtual environment with the virtualenv module:
py -m virtualenv <name of environment>
List the folder structure using the dir command:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 120


504 – Web Services and Framework (TYBCA Sem-V)

dir *<project name>*

The project directory shows the newly created environment:


Step 3: Activate the Environment
Activate the virtual environment before installing Flask. The name of the
activated environment shows up in the CLI after activation.
Activate the Environment on Windows
For Windows, activate the virtual environment with:

<name of environment>\Scripts\activate
Step 4: Install Flask
Install Flask within the activated environment using pip:
pip install Flask
Flask is installed automatically with all the dependencies.
Step 5: Test the Development Environment
1. Create a simple Flask application to test the newly created development
environment.
2. Make a file in the Flask project folder called hello.py.
3. Edit the file using a text editor and add the following code to make an application
that prints "Hello world!":
from flask import Flask
app = Flask(__name__)
@app.route('/')
def helloworld():
return 'Hello world!'

4. Save the file and close.


5. Using the console, navigate to the project folder using the cd command.
6. Set the FLASK_APP environment variable.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

 For Windows:
setx FLASK_APP "hello.py"
7. Run the Flask application with:
flask run

The output prints out a confirmation message and the address.

8. Copy and paste the address into the browser to see the project running:
To View Video: https://www.youtube.com/watch?v=QjtW-wnXlUY
https://www.youtube.com/watch?v=QjtW
5.1.1 Web Server Gateway Interface
WSGI refers to Web Server Gateway Interface. WSGI plays a vital role at the
time when you deploy your Django or Flask application.
WSGI is a specification that describes the communication between web
servers and Python web applications or frameworks
frameworks.. It explains how a web server
communicates with python web applications/frameworks and how web
applications/frameworks can be chained for processing a request.
How does WSGI work?
Now, let’s have a look at how WSGI work. So, to obtain a clear understanding of
WSGI, let us assume a casee scenario where you have a web application developed in
Django or Flask application as shown in the figure

The above figure represents your Django/Flask application.


504 – Web Services and Framework (TYBCA Sem-V)

Since a web application is deployed in the web server. The figure below

represents the web server that obtains requests from various users.

The web server which obtains requests from the users.

The above web server can be apache, NGINX, etc. server which is responsible
for handling various static files and caching purposes. Furthermore, you can also use
the server as a load balancer if you are willing to scale multiple applications.

How can a web server interact with the Python application?

The figure representing problem in the interaction between Python application


and a web server.
504 – Web Services and Framework (TYBCA Sem-V)

So, now a problem arises as a web server has to interact with a Python
application.
Hence, a mediator is required for carrying out the interaction between the web
servers and the Python application. So, the standard for carrying out communication
between the web server and Python application is WSGI(Web Server Gateway
Interface).
Now, web server is able to send requests or communicate with WSGI
containers. Likewise, Python application provides a ‘callable’ object which contains
certain functionalities that are invoked by WSGI application which are defined as per
the PEP 3333 standard. Hence, there are multiple WSGI containers available such as
Gunicorn, uWSGI, etc.
The figure below represents the communication that is carried out between
web server, WSGI, and Python application.
Communication between user, web server, WSGI, and Python application.
There are multiple WSGI containers that are available today. Hence, a WSGI
container is required to be installed in the project so that a web server can
communicate to a WSGI container which further communicates to the Python
application and provides the response back accordingly. Finally, when the web server
obtains the response, it is sent back to the web browser/users.

Why use the WSGI rather than directly pointing the web server to the Django or
Flask application?
If you directly point your web server to your application, it reduces
the flexibility of your application. Since your web server now directly points to your
web application, you are unable to swap out web stack components. Now, let’s have a
look at an example to make you clear about the applicability of WSGI. For instance,
today you have decided to deploy your application using Gunicorn but after some
years you decide to switch from Gunicorn to mod_wsgi. Now, in this case, you can
easily switch to mod_wsgi without making any changes in the application or
504 – Web Services and Framework (TYBCA Sem-V)

framework that implements WSGI. Hence, WSGI provides flexibility to your


application.
Another reason for using WSGI is due to its scalability. Once your application
is live, up and running there can be thousands of requests in your application. Hence,
WSGI is capable of serving thousands of requests at a time. As we know, the WSGI
server is responsible for handling the requests from the web server and takes decision
for carrying out the communication of those requests to an application framework’s
process. Here, we can divide the responsibilities among the servers for scaling web
traffic.
5.1.2 Web template engine (Jinja2)
Jinja2 is a modern day templating language for Python developers. It was made
after Django’s template. It is used to create HTML, XML or other markup formats that
are returned to the user via an HTTP request.
Jinja is a fast, expressive, extensible templating engine. Special placeholders in
the template allow writing code similar to Python syntax. Then the template is passed
data to render the final document.
It includes:
 Template inheritance and inclusion.
 Define and import macros within templates.
 HTML templates can use autoescaping to prevent XSS from untrusted user
input.
 A sandboxed environment can safely render untrusted templates.
 Async support for generating templates that automatically handle sync and
async functions without extra syntax.
 I18N support with Babel.
 Templates are compiled to optimized Python code just-in-time and cached, or
can be compiled ahead-of-time.
 Exceptions point to the correct line in templates to make debugging easier.
 Extensible filters, tests, functions, and even syntax.
Jinja’s philosophy is that while application logic belongs in Python if possible, it
shouldn’t make the template designer’s job difficult by restricting functionality too
much.
5.1.3 Creating the Flask Class object
The flask object implements a WSGI application and acts as the central object. It
is passed the name of the module or package of the application. Once it is created it
will act as a central registry for the view functions, the URL rules, template
configuration and much more.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 125


504 – Web Services and Framework (TYBCA Sem-V)

class flask.Flask(import_name, static_path=None, static_url_path=None, static_fold


er='static', template_folder='templates', instance_path=None, instance_relative_co
nfig=False)
The name of the package is used to resolve resources from inside the package
or the folder the module is contained in depending on if the package parameter
resolves to an actual python package (a folder with an __init__.py file inside) or a
standard module (just a .py file).
Usually you create a Flask instance in your main module or in the __init__.py file
of your package like this:
from flask import Flask
app = Flask(__name__)
The idea of the first parameter is to give Flask an idea what belongs to your
application. This name is used to find resources on the file system, can be used by
extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single
module, __name__ is always the correct value. If you however are using a package, it’s
usually recommended to hardcode the name of your package there.
For example if your application is defined in yourapplication/app.py you should
create it with one of the two versions below:
app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])
Why is that? The application will work even with __name__, thanks to how
resources are looked up. However it will make debugging more painful. Certain
extensions can make assumptions based on the import name of your application. For
example the Flask-SQLAlchemy extension will look for the code in your application
that triggered an SQL query in debug mode. If the import name is not properly set up,
that debugging information is lost. (For example it would only pick up SQL queries
in yourapplication.app and not yourapplication.views.frontend)
New in version 0.7: The static_url_path, static_folder,
and template_folder parameters were added.
New in version 0.8: The instance_path and instance_relative_config parameters
were added.
 import_name – the name of the application package
 static_url_path – can be used to specify a different path for
the static files on the web. Defaults to the name of
the static_folder folder.
Parameters:  static_folder – the folder with static files that should be
served at static_url_path. Defaults to the 'static' folder in the
root path of the application.
 template_folder – the folder that contains the templates
that should be used by the application. Defaults

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 126


504 – Web Services and Framework (TYBCA Sem-V)

to 'templates' folder in the root path of the application.


 instance_path – An alternative instance path for the
application. By default the folder 'instance' next to the
package or module is assumed to be the instance path.
 instance_relative_config – if set to True relative filenames
for loading the config are assumed to be relative to the
instance path instead of the application root.
5.1.4 Creating and hosting first basic Flask App.
Flask is a small and lightweight Python web framework that provides useful
tools and features that make creating web applications in Python easier. It gives
developers flexibility and is a more accessible framework for beginners to
programming, since you can build a web application quickly using only a single Python
file.
5.1.4.1route(), run(), add_url()_rule()
App routing is used to map the specific URL with the associated function that is
intended to perform some task.
In our first application, the URL ('/') is associated with the home function that
returns a particular string displayed on the web page.
In other words, we can say that if we visit the particular URL mapped to some
particular function, the output of that function is rendered on the browser's screen.
Example
from flask import Flask
app = Flask(__name__)

@app.route('/home')
def home():
return "hello, welcome to our website";

if __name__ =="__main__":
app.run(debug = True)

Flask facilitates us to add the variable part to the URL by using the section. We
can reuse the variable by adding that as a parameter into the view function. Consider
the following example.
Example
from flask import Flask
app = Flask(__name__)
@app.route('/home/<name>')
def home(name):
return "hello,"+name;
if __name__ =="__main__":
app.run(debug = True)

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 127


504 – Web Services and Framework (TYBCA Sem-V)

It will produce the following result on the web browser.

The converter can also be used in the URL to map the specified variable to the
particular data type. For example, we can provide the integers or float like age or
salary respectively.
Example
from flask import Flask
app = Flask(__name__)
@app.route('/home/<int:age>')
def home(age):
return "Age = %d"%age;
if __name__ =="__main__":
app.run(debug = True)

The following converters are used to convert the default string type to the associated
data type.
string: default
504 – Web Services and Framework (TYBCA Sem-V)

int: used to convert the string to the integer

float: used to convert the string to the float.

path: It can accept the slashes given in the URL.

add_url_rule() function
There is one more approach to perform routing for the flask web application
that can be done by using the add_url() function of the Flask class. The syntax to use
this function is given below.
add_url_rule(<url rule>, <endpoint>, <view function>)

This function is mainly used in the case if the view function is not given and we
need to connect a view function to an endpoint externally by using this function.
Consider the following example.
Example
from flask import Flask
app = Flask(__name__)
def about():
return "This is about page";
app.add_url_rule("/about","about",about)
if __name__ =="__main__":
app.run(debug = True)

5.2 URL building and its advantages


5.2.1 url_for() function
The url_for() function is used to build a URL to the specific function
dynamically. The first argument is the name of the specified function, and then we can
pass any number of keyword argument corresponding to the variable part of the URL.
This function is useful in the sense that we can avoid hard-coding the URLs into
the templates by dynamically building them using this function.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

Consider the following python flask script.


Example
from flask import *

app = Flask(__name__)
@app.route('/admin')
def admin():
return 'admin'

@app.route('/librarion')
def librarion():
return 'librarion'
@app.route('/student')
def student():
return 'student'

@app.route('/user/<name>')
def user(name):
if name == 'admin':
return redirect(url_for('admin'))
if name == 'librarion':
return redirect(url_for('librarion'))
if name == 'student':
return redirect(url_for('student'))
if __name__ =='__main__':
app.run(debug = True)

The above script simulates the library management system which can be used
by the three types of users, i.e., admin, libraria
librarian,
n, and student. There is a specific
function named user() which recognizes the user the re redirect
direct the user to the exact
function which contains the implementation for this particular function.
504 – Web Services and Framework (TYBCA Sem-V)

For example, the URL http://localhost:5000/user/admin is redirected to the URL


http://localhost:5000/admin, the URL localhost:5000/user/librarion, is redirected to
the URL http://localhost:5000/librarion, the URL http://localhost:5000/user/student
is redirected to the URL http://localhost/student.
Benefits of the Dynamic URL Building
 It avoids hard coding of the URLs.
 We can change the URLs dynamically instead of remembering the manually
changed hard-coded URLs.
 URL building handles the escaping of special characters and Unicode data
transparently.
 The generated paths are always absolute, avoiding unexpected behavior of
relative paths in browsers.
 If your application is placed outside the URL root, for example, in /myapplication
instead of /, url_for() properly handles that for you.
5.3 Flask HTTP methods:
HTTP is the hypertext transfer protocol which is considered as the foundation
of the data transfer in the world wide web. All web frameworks including flask need to
provide several HTTP methods for data communication.
The methods are given in the following table.
SN Method Description
1 GET It is the most common method which can be used to send data in the
unencrypted form to the server.
2 HEAD It is similar to the GET but used without the response body.
3 POST It is used to send the form data to the server. The server does not cache
the data transmitted using the post method.
4 PUT It is used to replace all the current representation of the target
resource with the uploaded content.
5 DELETE It is used to delete all the current representation of the target resource
specified in the URL.
We can specify which HTTP method to be used to handle the requests in the
route() function of the Flask class. By default, the requests are handled by the GET()
method.
POST Method
To handle the POST requests at the server, let us first create a form to get some
data at the client side from the user, and we will try to access this data on the server
by using the POST request.
login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "post">

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 131


504 – Web Services and Framework (TYBCA Sem-V)
Sem

<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
</body>
</html>

Now, Enter the following code into the script named post_example.py.
post_example.py
from flask import *
app = Flask(__name__)

@app.route('/login',methods = ['POST'])
def login():
uname=request.form['uname']
passwrd=request.form['pass']
if uname=="ayush" and passwrd=="google":
return "Welcome %s" %uname
if __name__ == '__main__':
app.run(debug = True)

Now, start the development server by running the script using python
post_exmple.py and open login.html on the web browser as shown in the following
image.

Give the required input and click Submit, we will get the following result.
Hence, the form data is sent to the development server by using the post method.
GET Method
504 – Web Services and Framework (TYBCA Sem-V)
Sem

Let's consider the same example for the Get method. However, there are some
changes in the data retrieval syntax on the server side. First, create a form as
login.html.
login.html
<html>
<body>
<form action = "http://localhost:5000/login" method = "get">
<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
</body>
</html>

Now, create the following python script as get_example.py.


get_example.py
from flask import *
app = Flask(__name__)

@app.route('/login',methods = ['GET'])
def login():
uname=request.args.get('uname')
passwrd=request.args.get('pass')
if uname=="ayush" and passwrd=="google":
return "Welcome %s" %uname

if __name__ == '__main__':
app.run(debug = True)

Now, open the HTML file, login.html on the web browser and give the required input.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

Now, click the submit button.

As we can check the result. The data sent using the get() method is retrieved on the
development server.
The data is obtained by using the following line of code.

uname = request.args.get('uname')

Here, the args is a dictionary object which contains the list of pairs of form parameter
and its corresponding value.
In the above image, we can also check the URL which also contains the data sent with
the request to the server. This is an important difference between the GET requests
and the POST requests as the data sent to the server is not shown in the URL on the
browser in the POST requests.
HEAD method
HEAD is a request method supported by HTTP used by the World Wide Web.
The HEAD method asks for a response identical to that of a GET request, but without
the response body. This is useful for retrieving meta
meta-information
information written in response
headers, without having to transport the entire content.
How to make HEAD request through Python Requests
Python’s
’s requests module provides in
in-built method called head() for making a
HEAD request to a specified URI.
Syntax
requests.head(url, params={key: value}, args)
Example

import requests
# Making a HEAD request
r = requests.head('https://httpbin.org/
https://httpbin.org/', data ={'key':'value'})
# check status code for response received
# success code - 200
print(r)
504 – Web Services and Framework (TYBCA Sem-V)

# print headers of request


print(r.headers)
# checking if request contains any content
print(r.content)

save this file as request.py and through terminal run,


python request.py
Output

DELETE Method
DELETE is a request method supported by HTTP used by the World Wide Web. The
DELETE method deletes the specified resource. As with a PUT request, you need to
specify a particular resource for this operation. A successful response SHOULD be 200
(OK) if the response includes an entity describing the status, 202 (Accepted) if the
action has not yet been enacted, or 204 (No Content) if the action has been enacted
but the response does not include an entity.
How to make DELETE request through Python Requests
Python’s requests module provides in-built method called delete() for making a
DELETE request to a specified URI.
Syntax

requests.delete(url, params={key: value}, args)

Example
import requests
# Making a DELETE request
r = requests.delete('https://httpbin.org / delete', data ={'key':'value'})
# check status code for response received
# success code - 200
print(r)
# print content of request
print(r.json())
504 – Web Services and Framework (TYBCA Sem-V)

save this file as request.py and through terminal run,


python request.py
Output

PUT Method
PUT is a request method supported by HTTP used by the World Wide Web. The PUT
method requests that the enclosed entity be stored under the supplied URI. If the URI
refers to an already existing resource, it is modified and if the URI does not point to an
existing resource, then the server can create the resource with that URI.
How to make PUT request through Python Requests
Python’s requests module provides in-built method called put() for making a PUT
request to a specified URI.
Syntax
requests.put(url, params={key: value}, args)

Example

import requests
# Making a PUT request
r = requests.put('https://httpbin.org / put', data ={'key':'value'})
# check status code for response received
# success code - 200
print(r)
# print content of request
print(r.content)

save this file as request.py and through terminal run,


python request.py
504 – Web Services and Framework (TYBCA Sem-V)
Sem

Output –

Difference between PUT and POST methods


PUT POST
PUT request is made to a particular resource. If the POST method is used to request that the origin
Request-URI
URI refers to an already existing resource, server accept the entity enclosed in the
an update operation will happen, otherwise create request as a new subordinate
dinate of the resource
operation should happen if Request
Request-URI is a valid identified by the Request-URI
URI in the Request-
Request
resource URI (assuming client is allowed to Line. It essentially means that POST request-URI
request
determine resource identifier). should be of a collection URI.
Example Example
PUT /article/{article-id} POST /articles
PUT method is idempotent. So if you send retry a POST is NOT idempotent. So if you retry the
request multiple times, that should
ld be equivalent request N times, you will end up having N
to single request modification. resources with N different URIs created on
server.
Use PUT when you want to modify a single Use POST when you want to add a child resource
resource which is already a part of resources under resources collection.
collection. PUT overwrites the resource in its
entirety. Use PATCH if request updates part of the
resource.

Generally, in practice, always use PUT for UPDATE Always use POST for CREATE operations.
operations.

5.3.2 Dynamic Data Representation using Jinja2


Web 2.0 has introduced the concept of delivering user-centric
user centric interactive
content. In the very early stage of the internet, the content delivered had static files.
Fast forward to the current situation: Everything you consume is dynamically
generated. The website content changes according to the user inputs and the logic for
implementing such changes involves additional scripting via the server or client-side.
client
Web development using Python is one of the most preferred projects after Data
Science and Machine Learning. Every Python learner is advised to adopt at least one
504 – Web Services and Framework (TYBCA Sem-V)
Sem

web development framework using Python. Some of the most popular choices
include Flask, Django,, and FastAPI. One thing that is common among all these
frameworks is the use of templating engines.
Templating engines allow us to pass the data from the server-side
server side to HTML
pages (also support any text file and XML, CSV, LaTeX, etc) whenever the user makes
the request. This also allows us to build interactive websites with less effort plus the
support for the Object-Oriented
nted paradigm on the abstract level (inheritance) for web
pages nails it.
Jinja is one such template engine that is used extensively in Flask and FastAPI.
Django’s Templating engine is also very much similar to Jinja with a few
differences.Jinja templatingg comes pre-installed
pre installed with Flask and as an optional
requirement in FastAPI. The usage of the templating engine in both frameworks
remains the same.
We are able to use templates in flask for storing the non
non-changing
changing data, but we
can also use them dynamically
lly to show data using Jinja.. Jinja is used to write python-
python
like syntax in HTML files, which helps in using variables like functionality. In other
words, we can make dynamic templates also
also.
File structure

5.3.2.1Jinja2 Delimiters
Jinga 2 template engine provides some delimiters which can be used in the
HTML to make it capable of dynamic data representation. The template system
provides some HTML syntax which are placeholders for variables and expressions
that are replaced by their actual values when the template is rendered.
The jinga2 template engine provides the following delimiters to escape from
the HTML.
o {% ... %} for statements
o {{ ... }} for expressions to print to the template output
o {# ... #} for the comments that are not included in the template output
o # ... ## for line statements
Example
Consider the following example where the variable part of the URL is shown in
the HTML script using the {{ ... }} delimiter.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

message.html
<html>
<head>
<title>Message</title>
</head>
<body>
<h1>hi, {{ name }}</h1>
</body>
</html>

script.py
from flask import *
app = Flask(__name__)

@app.route('/user/<uname>')
def message(uname):
return render_template('message.html',name=uname)
if __name__ == '__main__':
app.run(debug = True)

The variable part of the URL http://localhost:5000/user/admin is shown in the


HTML script using the {{name}} placeholder.

Embedding Python statements in HTML


Due to the fact that HTML is a mark-up
mark up language and purely used for the
designing purpose, sometimes, in the web applications, we may need to execute the
statements for the general-purpose
purpose computations. For this purpose, Flask facilitates us
the delimiter
imiter {%...%} which can be used to embed the simple python statements into
the HTML.
Example
In the following example, we will print the table of a number specified in the
URL, i.e., the URL http://localhost:5000/table/10 will print the table of 10 on ththe
browser's window.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

Here, we must notice that the for-loop


for loop statement is enclosed inside {%...%}
delimiter, whereas, the loop variable and the number is enclosed inside {{ ... }}
placeholders.
script.py
from flask import *
app = Flask(__name__)

@app.route('/table/<int:num>')
def table(num):
return render_template('print-table.html',n=num)
table.html',n=num)
if __name__ == '__main__':
app.run(debug = True)

print-table.py
<html>
<head>
<title>print table</title>
</head>
<body>
<h2> printing table of {{n}}</h2>
{% for i in range(1,11): %}
<h3>{{n}} X {{i}} = {{n * i}} </h3>
{% endfor %}
</body>
</html>
504 – Web Services and Framework (TYBCA Sem-V)

Referring Static files in HTML


The static files such as CSS or JavaScript file enhance the display of an HTML
web page. A web server is configured to serve such files from the static folder in the
package or the next to the module. The static files are available at the path /static of
the application.
Example
In the following example, the flask script returns the HTML file,
i.e., message.html which is styled using the stylesheet style.css. The flask template
system finds the static CSS file under static/css directory. Hence the style.css is saved
at the specified path.
script.py
from flask import *
app = Flask(__name__)
@app.route('/')
def message():
return render_template('message.html')
if __name__ == '__main__':
app.run(debug = True)

message.html
<html>
<head>
<title>Message</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<h1>hi, welcome to the website</h1>
</body>
</html>

style.css
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 141


504 – Web Services and Framework (TYBCA Sem-V)
Sem

allinone.py
from flask import Flask, render_template_string, request

class CustomFlask(Flask):
jinja_options = Flask.jinja_options.copy()
jinja_options.update(dict(
block_start_string='<%',
block_end_string='%>',
variable_start_string='%%',
variable_end_string='%%',
comment_start_string='<#',
comment_end_string='#>',
))

app = CustomFlask(__name__)
app.config['DEBUG'] = True

@app.route("/")
def index():
template = """
<# this is a jinja2 comment #>
<% block stuff %>
<h1>Jinja2</h1>
<% for i in range(5) %>
<p>Hello %% name %%!</p>
<% endfor %>

<h1>Mustache</h1>
<p>{{something}}</p>
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
504 – Web Services and Framework (TYBCA Sem-V)

{{/first}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/items}}
<% endblock %>
"""
return render_template_string(template, name=request.values.get('name', Viral'))
if __name__ == "__main__":
app.run(use_debugger=True, use_reloader=True)

5.3.2.2Embedding Python statement in HTML


As we have seen in the file structure in previous section, for working with the
HTML files we need to consider the structure we have seen earlier. So we will keep all
the html files within the same directory say “templates”. Our data will be flew from the
python to these html files.
Once we are able to start and run flask server, we can start sending inputs from
the Python backend, and later on, we will see how inputs from web UI flow to the
backend processing and render that result on the website.
The main idea of using a templating engine in web development is to render
data dynamically in HTML files. To represent such data forms in HTML files, there are
3 types of syntaxes are available:
1. Expressions: These are the simple variable representation that is used for
displaying any data type from the Python backend. It is similar to print
statements in programming languages. The syntax is {{ ... }}
2. Statements: These syntaxes are used to implement control structures such as
for loop, if-else, macros, blocks, imports, and much more things. The syntax
is {% ... %}
3. Comments: One can also add Jinja comments to the template codes. These are
represented as {# … #} .
Let’s try passing some values from the Python server to the Jinja templates.
Simply create a new HTML file under the “templates” directory. In this HTML file,
expression syntax has been used to print the value from the server to the HTML
webpage. Here are the contents of the new.html file:
{{first_name}}, {{last_name}} :: {{article_title}}
The above content expects 3 parameters to be passed from the backend. To
render this HTML template with actual values from the Python backend, you need to
use the render_template method from the flask package. This method takes in the
template name, followed by the values to be passed to the HTML template. The
parameter’s name should be the same as the name used in the HTML template. The
following snippet shows this:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 143


504 – Web Services and Framework (TYBCA Sem-V)

from flask import Flask, render_template


app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('new.html',
first_name=Viral',
last_name="Polishwala",
article_title="Jinja HTML ")
if __name__ == "__main__":
app.run(debug=True)

5.3.2.3Static File reference in HTML


Web applications often require static files, such as javascript files or CSS files
that support Web display. Typically, we configure the Web server and it provides us
with this. But during development Flask development, Python parses all web requests.
To solve this, these files are placed in the static folder, which will be available in the
applications /static kind of folder.
Where to place static files
The URL of the special endpoint static is used to generate a static file. In your
programs directory, create a new directory named static. In this directory you can
place images, javascript files, css files and many other files that don’t need a Python
backend.
About url_for() function
url_for() function in Flask allows us to create a absolute URL of resources. It
takes two parameters:
1: Endpoint
2: Values
For example:
url_for('static', filename = 'name_of_file')
This will generate the path by using the file name present in the static folder.
Example
In the following example, the javascript function defined in the hello.js is called
on the OnClick event of the HTML button in index.html, which is rendered on the “/“
URL of the Flask application.

from flask import Flask, render_template


app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug = True)

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 144


504 – Web Services and Framework (TYBCA Sem-V)

Then index.html
<html>
<head>
<script type = "text/javascript"
src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

Add a javascript file, hello.js


function sayHello() {
alert("Hello World")
}
One more such example is given below: for index.html
<html>
<head>
<title>Static File</title>
<link href="{{url_for('static', filename = 'style.css')}}" rel="stylesheet">
<script src="{{url_for('static', filename = 'script.js')}}"></script>
</head>
<body>
<h3>Hello World!</h3>
</body>
</html>

5.4 Flask Request Object (Forms, args, files, redirect)


A Flask Request Object is an object that contains all of the data about a
particular HTTP request. It contains information about the HTTP method, as well as
any data that was sent in with that request, such as form fields or file uploads. It also
has methods for accessing information in the body of an HTTP request.
How it is different from regular request?
 A Flask Request Object is a request object that has been extended with additional
functionality. This makes it a more powerful and flexible request object.
 Flask Request Objects are great for making it easier to create RESTful APIs. They're
also useful for handling data validation, or for creating custom methods on the fly.
Advantages
The advantages of using a Flask Request Object are:
 It can be used to fetch data from the database and pass it to templates.
 It is an easy way to write unit tests for your app.
 It can be used to handle cookies and sessions in your app.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 145


504 – Web Services and Framework (TYBCA Sem-V)

Use of Request Object


A request object is a built-in object which is used to represent an HTTP request.
It contains information such as the URL, headers, and data.
The request object is the first argument passed to the view function. It contains
all of the information about what has been requested by the client. This includes, but
is not limited to, the URL, headers, data, cookies and more. It can be used for many
things such as authentication and authorization.
The flask object has a significant role to play because it is the request object
that holds the data when the data is sent form an html form in the form of information
until it reaches the server. The request object performs all the data processing, error
handling, and other function too, while transferring the data to the server.
Or we can say that, In the client-server architecture, the request object contains
all the data that is sent from the client-side to the server using HTTP methods like get,
post. And all that data is temporarily stored in the request object till the server
receives it.

SN Attribute Description

1 Methods By which data is sent from the client-side. i.e. get or post.

2 File It holds the info about the uploaded file.

3 Cookies These are the temporary short files that hold the names and values of cookies, which
helps to track user session on the client-side.

4 Args Arguments are fetched from the URL address. It is part of the URL address that is
declared in the URL address just after the '?'.

5 Form It stores various key-value of form parameters.

5.4.1 Form request object, render_template() method, Form data handling


In the following example, the "URL" displays a web page ("customer1.html"), that
contains a simple html form that is used to take the information as the input from the
customer. The information filled by the user in the html form is sent to
the http://localhost:5000/success using the POST method. The render_datafunction()
function receives all information from the request object and displays it on the
result_data.html page.
This application has three files, which are script2.py, customer.html, and
result_data.html.
1. Script2.py
from flask import *
app = Flask(__name__)
@app.route('/')
def customer():

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 146


504 – Web Services and Framework (TYBCA Sem-V)

return render_template('customer1.html')
@app.route('/success',methods = ['POST', 'GET'])
def render_datafunction():
if request.method == 'POST':
result = request.form
return render_template("result_data.html",result = result)
if __name__ == '__main__':
app.run(debug = True)

2. Customer1.html
<html>
<body>
<h3>Customer Registration</h3>
<p>Fill this form.</p>
<form action = "http://localhost:5000/success" method = "POST">
<p>Name <input type = "text" name = "entername" /></p>
<p>Email <input type = "email" name = "enteremail" /></p>
<p>Contact <input type = "text" name = "entercontact" /></p>
<p>Pin code <input type ="number" name = "pin" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>

3. Result_data.html
<!doctype html>
<html>
<body>
<p><strong>Thanks for the registration. Confirm your details</strong></p>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>

Firstly you must run the script.py file by using the command python script.py. This
will start the development server on the localhost:5000, which can be later accessed
on the browser, as given below:

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 147


504 – Web Services and Framework (TYBCA Sem-V)

Now click on the submit button, and output is shown in the given screenshot.

flask.render_template(template_name_or_list, **context)
Renders a template from the template folder with the given context.
Parameters
 template_name_or_list (Union[str, jinja2.environment.Template, List[Union[str,
jinja2.environment.Template]]]) – the name of the template to be rendered, or
an iterable with template names the first one existing will be rendered
 context (Any) – the variables that should be available in the context of the
template.
Return type
str
504 – Web Services and Framework (TYBCA Sem-V)

5.4.2 Flask Session, Creating Session, Session Variable, Session.pop()


In the session, the data is saved on the server. It can be determined as a time
interval in which the client accesses the server until the user logs off. The data
between them is stored in a temporary folder on the server. Each user is assigned a
specific session ID. The Session object is a dictionary that contains the key-value pair
of variables associated with the session. A SECRET_KEY is used to store encrypted
data in the cookie.
The concept of session is very similar to that of a cookie. However, session data
is stored on the server.
The session can be defined as the duration during which a user log in into the
server and disconnects. The data used to track this session is stored in the temporary
directory of the server.
Session data is stored on top of cookies, and the server cryptographically signs.
The syntax which is used to set the session variable to a specific value on the
server are given below:-
For example:
Session[key]= value // stores the session value

To remove a session variable, use the pop() method on the session object and
mention the variable to be removed.
Session.pop(key, None) // releases a session variable

Let's see a simple example to understand how we can set and get the session variable.
Session.py
from flask import *
app = Flask(__name__)
app.secret_key = "abc"
@app.route('/')
def home():
res = make_response("<h4>session variable is set, <a href='/get'>Get Variable</a></h4>")
session['response']='session#1'
return res;
@app.route('/get')
def getVariable():
if 'response' in session:
s = session['response'];
return render_template('getsession.html',name = s)
if __name__ == '__main__':
app.run(debug = True)

getsession1.html
<html>
<head>

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 149


504 – Web Services and Framework (TYBCA Sem-V)

<title>getting the session</title>


</head>
<body>
<p>now session is set with value: <strong>{{name}}</strong></p>
</body>
</html>

Now run the Session.py file

Now click on the get variable.

Login Application in the flask using Session


Now let's create a login application in a flask where a home page is shown to the user
as given below
Loginpage.py
from
flask import *
504 – Web Services and Framework (TYBCA Sem-V)

app = Flask(__name__)
app.secret_key = "ayush"
@app.route('/')
def home():
return render_template("homepage2.html")
@app.route('/login')
def login():
return render_template("loginpage3.html")
@app.route('/success',methods = ["POST"])
def success():
if request.method == "POST":
session['email']=request.form['email']
return render_template('success3.html')
@app.route('/logout')
def logout():
if 'email' in session:
session.pop('email',None)
return render_template('logoutpage2.html');
else:
return '<p>user already logged out</p>'
@app.route('/profile')
def profile():
if 'email' in session:
email = session['email']
return render_template('profile.html',name=email)
else:
return '<p>Please login first</p>'
if __name__ == '__main__':
app.run(debug = True)

homepage2.html
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome to the website</h3>
<a href = "/login">login</a><br>
<a href = "/profile">view profile</a><br>
<a href = "/logout">Log out</a><br>
</body>
</html>

Loginpage3.html
<html>
<head>

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 151


504 – Web Services and Framework (TYBCA Sem-V)

<title>login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/success">
<table>
<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>

Success.html
<html>
<head>
<title>success</title>
</head>
<body>
<h2>Login successful</h2>
<a href="/profile">View Profile</a>
</body>
</html>

Logoutpage2.html
<html>
<head>
<title>logout</title>
</head>
<body>
<p>logout successful, click <a href="/login">here</a> to login again</p>
</body>
</html>

Now lets run the loginpage1.py file from cmd as shown below
504 – Web Services and Framework (TYBCA Sem-V)

Now click on the login button, if you directly click on the view profile then it may show
some warning as shown below

Now click on the login button.


Now click on the submit button as shown.

Now click on the view profile button.


504 – Web Services and Framework (TYBCA Sem-V)

5.4.3 File Uploading: request.files(), object, save() method, saving file to


specific folder
Uploading files using the Flask framework is a straightforward task. You need
an HTML form with the enctype attribute and the URL manager, which retrieves the
file and saves the object in the desired location. These files are temporarily stored on
the server and then in the desired location.
Or we can say that File Uploading is the process of transmitting binary or
standard files to the server. Flask makes it easy for us to upload files. All we need is to
have an HTML form with a set of multipart / form-data encryption.
The server-side globe script retrieves the requested object file using the
request — files [] object. Once the file is loaded correctly, it is saved in the desired
location on the server.
The uploaded file is saved in the temporary directory of the server for a while
before being saved in the desired location.
However, we can mention the path to the folder in which the file should be
uploaded to the server, and the maximum size of the uploaded file should also be
mentioned. This can be done in the configuration settings of the global object.
app.config['MAX_CONTENT-PATH'] = it is used to specify the maximum size of the file to be uploaded.

app.config['UPLOAD_FOLDER'] = it is used to specify the location or the upload folder.

We can easily understand the file uploading with the help of an example
In this example, we will provide a file selector (file_upload_form.html) to the
user where the user can select a file from the file system and send it to the server.
On the server-side, the file is retrieved using the request.files ['file'] object and
saved in the server location.
Fileuploadform1.html
<html>
<head>
<title>upload</title>
</head>
<body>
<form action = "/success4" method = "post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type = "submit" value="Upload">
</form>
</body>
</html>

Success4.html
<html>
<head>
<title>success</title>

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 154


504 – Web Services and Framework (TYBCA Sem-V)

</head>
<body>
<p>File has been uploaded successfully</p>
<p>File Name: {{name}}</p>
</body>
</html>

Uploladpagefile.py
from flask import *
app = Flask(__name__)
@app.route('/')
def upload():
return render_template("fileuploadform1.html")
@app.route('/success', methods = ['POST'])
def success():
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
return render_template("success4.html", name = f.filename)
if __name__ == '__main__':
app.run(debug = True)

Now let’s run the uploadpagefile.py.


An HTML form is displayed to the user.

Click on the Browse button so that we can explore the file system and search
the appropriate file.
Now we have to choose a file, as shown below.
504 – Web Services and Framework (TYBCA Sem-V)

Now double click on the file.

Here click on the Upload button. Then user get a message of successful file uploading
as given below:-

We can confirm this by checking in the directory where upload.py is located, as shown
in the image below.
504 – Web Services and Framework (TYBCA Sem-V)
Sem

5.4.4 Redirecting: redirect() method, location, status code and response


Redirect is also a function provided by the flask. It is called redirect() function.
When this function is called, it returns a response object and also redirects the user to
another location with the specific code.
The syntax of the redirect function is given below:
Flask.redirect(location, status code, response)

Here the first parameter is the location that is referred to as a target place
where the user is going to be redirected.
The second parameter is the status code. It is sent to the header of the
browser. The default code is 302, which stands for "found." And the third one is the
response, and it is used to instantiate the response.
We can understand this with the help of an example.
First of all,, we have to create three pages.
 Homepage=home3.html
 Login page =login3.html
 Python script=redirect.py
Both html file must be saved in the template folder that we made earlier
flask_app/templates and .py file saved to the flask_app folder.
Home3.html
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome</h3>
<a href = "/login">login</a><br>
504 – Web Services and Framework (TYBCA Sem-V)

</html>

login3.html
<html>
<head>
<title>login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/validate">
<table>
<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>

redirect.py
from
flask import *
app = Flask(__name__)
@app.route('/')
def home_page ():
return render_template("home3.html")
@app.route('/login')
def login_page():
return render_template("login3.html");
@app.route('/validate', methods = ["POST"])
def validate():
if request.method == 'POST' and request.form['pass'] == 'Akash':
return redirect(url_for("success"))
return redirect(url_for("login"))
@app.route('/success')
def success():
return "logged in successfully"
if __name__ == '__main__':
app.run(debug = True)

Run the redirect.py file, and the output is given below.


Now click on the login.

SUTEX BANK COLLEGE OF COMPUTER APPLICATIONS & SCIENCE 158


504 – Web Services and Framework (TYBCA Sem-V)

After clicking on the login button, a html form will appear. Fill this form and click on
the Submit button.

If the user enters the wrong details like an incorrect email id or password, then the
page is going to redirect to the same page again and again until the user enters the
correct details.
Example:
If the user enters an incorrect password, then it redirects the login page back again,
and it will show notification, i.e., You have entered incorrect Email or password.
504 – Web Services and Framework (TYBCA Sem-V)

When the correct key is entered, the output is.

Abort function is a function of the flask. It is used in particular scenarios, in which


some kind of errors occurred from the client-side in the request. It also provides a
plain blank white error page for the user with basic information about the error.
Syntax of abort() function.
Flask.abort(code)
Some of the most common error codes depend on the particular errors are as follows.
 400
504 – Web Services and Framework (TYBCA Sem-V)

 401

 403
504 – Web Services and Framework (TYBCA Sem-V)

 404

 406

 415
504 – Web Services and Framework (TYBCA Sem-V)

We can understand the working of the abort() function with the help of an example.
Note:- In this example, we use both the html templates and the same files that we used
in the example of redirect() function, so we don't have to create new files.
Abort1.py
from flask import *
app = Flask(__name__)
@app.route('/')
def home_page ():
return render_template("home3.html")
@app.route('/login')
def login_page():
return render_template("login3.html");
@app.route('/validate', methods = ["POST"])
def validate_code():
if request.method == 'POST' and request.form['pass'] == 'Akash':
return redirect(url_for("success"))
else:
abort(400)
@app.route('/success')
def success():
return "logged in successfully"
if __name__ == '__main__':
app.run(debug = True)

Output
Click on the login.

Fill the correct Email because the code has validation. Click on the Submit button to
see how abort() function works.
504 – Web Services and Framework (TYBCA Sem-V)

You might also like