GMR Institute of Technology Rajam, AP: 1. Objective
GMR Institute of Technology Rajam, AP: 1. Objective
REV.: 00
Rajam, AP
(An Autonomous Institution Affiliated to JNTUGV, AP)
Cohesive Teaching – Learning Practices (CTLP)
Class 4th Sem – B. Tech Department: CSE
Course Web Coding and Development Course Code 21CS405
Prepared by Dr. Ch Sekhar
Lecture Topic Introduction to Flask, Virtual Environment, features of flask, url building, routing,
Templates and Jinja Code, Rendering Templates, Static files, Building Forms,
Sending Form data to Templates,
Course Outcome(s) CO 5,6 Program Outcome (s) PO2,PO3
Duration 1 hour Lecture 1-6 Unit IV
Pre-requisite (s) HTML, CSS, Bootstrap, JavaScript and Database
1. Objective
Develop Dynamic Web Pages using Flask
Make use of database connectivity to communicate database server from web server.
5. Evocation
6. Deliverables
Lecture-1
Basics of flask
This Flask Tutorial is the latest and comprehensive guide designed for beginners and professionals to
learn Python Flask framework, which is one of the most popular Python-based web frameworks.
Whether you are a beginner or an experienced developer, this tutorial is specially designed to help you
learn and master Flask and build your own real-world web applications. This Flask Tutorial covers a
wide range of topics from basic concepts such as setup and installation to advanced concepts like user
authentication, database integration, and deployment.
WSGI
Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application
development. WSGI is a specification for a universal interface between the web server and the web
applications.
Werkzeug
It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This
enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its
bases.
Jinga2
Jinga2 is a popular templating engine for Python. A web templating system combines a template with
a certain data source to render dynamic web pages.
Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet
extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form
a validation support. Instead, Flask supports the extensions to add such functionality to the
application. Some of the popular Flask extensions are discussed later in the tutorial.
Syntax: flask.redirect(location,code=302)
Parameters:
• location(str): the location which URL directs to.
• code(int): The status code for Redirect.
• Code: The default code is 302 which means that the move is only temporary.
• Return: The response objects and redirects the user to another target location with the specified
code.
app.py
# import flast module
from flask import Flask, redirect
# instance of flask application
app = Flask(__name__)
# home route that redirects to
# helloworld page
@app.route("/")
def home():
return redirect("/helloworld")
# route that returns hello world text
@app.route("/helloworld")
def hello_world():
return "<p>Hello, World from \
redirected page.!</p>"
if __name__ == '__main__':
app.run(debug=True)
Output:
We hit the base URL in the browser as shown below. As soon we hit the URL flask application
returns the redirect function and redirects to the given URL.
URL Binding
The url_for() function is very useful for dynamically building a URL for a specific function. The
function accepts the name of a function as first argument, and one or more keyword arguments, each
corresponding to the variable part of URL.
The following script demonstrates use of url_for() function.
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/admin')
def hello_admin():
return 'Hello Admin'
@app.route('/guest/<guest>')
def hello_guest(guest):
return 'Hello %s as Guest' % guest
@app.route('/user/<name>')
def hello_user(name):
if name=='admin':
return redirect(url_for('hello_admin'))
else:
return redirect(url_for('hello_guest',guest=name))
if __name__ == '__main__':
app.run(debug=True)
The above script has a function user(name) which accepts a value to its argument from the URL.
The User() function checks if an argument received matches ‘admin’ or not. If it matches, the
application is redirected to the hello_admin() function using url_for(), otherwise to the hello_guest()
function passing the received argument as guest parameter to it.
Save the above code and run from Python shell.
Open the browser and enter URL as:
http://localhost:5000/hello/admin
The function render_template provided by Flask integrates the Jinja2 template engine with the
application. This function takes the filename of the template as its first argument. Any additional
arguments are key/value pairs that represent actual values for variables referenced in the template. In
this example, the second template is receiving a name variable.
Keyword arguments like name=name in the previous example are fairly common but may seem
confusing and hard to understand if you are not used to them. The “name” on the left side represents
he argument name, which is used in the placeholder written in the template. The “name” on the right
side is a variable in the current scope that provides the value for the argument of the same name.
Variables
The {{ name }} construct used in the template shown in Example 3-2 references a
variable, a special placeholder that tells the template engine that the value that goes in
that place should be obtained from data provided at the time the template is rendered.
Jinja2 recognizes variables of any type, even complex types such as lists, dictionaries
and objects. The following are some more examples of variables used in templates:
<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>
Variables can be modified with filters, which are added after the variable name with a
pipe character as separator. For example, the following template shows the name variable
capitalized:
Hello, {{ name|capitalize }}
Control Structures
Jinja2 offers several control structures that can be used to alter the flow of the template. This section
introduces some of the most useful ones with simple examples. The following example shows how
conditional statements can be entered in a template:
{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}
Another common need in templates is to render a list of elements. This example shows how this can
be done with a for loop:
<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>
Jinja2 also supports macros, which are similar to functions in Python code. For example:
{% macro render_comment(comment) %}
<li>{{ comment }}</li>
{% endmacro %}
<ul>
{% for comment in comments %}
{{ render_comment(comment) }}
{% endfor %}
</ul>
To make macros more reusable, they can be stored in standalone files that are then imported from all
the templates that need them:
{% import 'macros.html' as macros %}
<ul>
{% for comment in comments %}
{{ macros.render_comment(comment) }}
{% endfor %}
</ul>
Portions of template code that need to be repeated in several places can be stored in a separate file and
included from all the templates to avoid repetition:
{% include 'common.html' %}
Yet another powerful way to reuse is through template inheritance, which is similar to class
inheritance in Python code. First, a base template is created with the name
base.html:
<html>
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Application</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
Here the block tags define elements that a derived template can change. In this example, there are
blocks called head, title, and body; note that title is contained by head. The following example is a
derived template of the base template:
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style>
</style>
{% endblock %}
{% block body %}
<h1>Hello, World!</h1>
{% endblock %}
The extends directive declares that this template derives from base.html. This directive is followed by
new definitions for the three blocks defined in the base template, which are inserted in the proper
places. Note that the new definition of the head block, which is not empty in the base template, uses
super() to retain the original contents.
Now, this will set up the Flask starting point to that file we created, so once we start the server the
Flask server will find the way to the file “server.py”
To run the server, enter the command :
flask run
This will run the server and how smartly it detected the server.py file as our actual flask app. If you go
to the URL “http://localhost:5000”, you would see nothing than a Not Found message this is because
we have not configured our web server to serve anything just yet. You can press CTRL + C to stop the
server
Creating Templates in a Flask Application
Now, we can move on to the goal of this article i.e. to render the template. To do that we need to first
create the templates, you can use any HTML template but for simplicity, I am going with a basic
HTML template. Before that, create a folder called “templates” in the current folder. Inside this
“templates” folder, all of the templates will be residing. Now let us create a basic HTML template:
This template must have some Jinja blocks that can be optionally replaced later. We start with a single
block called the body.
templates\index.html
HTML
<!DOCTYPE html>
<html>
<head>
<title>FlaskTest</title>
</head>
<body>
<h2>Welcome To GFG</h2>
<h4>Flask: Rendering Templates</h4>
<!-- this section can be replaced by a child document -->
{% block body %}
<p>This is a Flask application.</p>
{% endblock %}
</body>
</html>
Adding Routes and Rendering Templates
A route is a mapping of a URL with a function or any other piece of code to be rendered on the
webserver. In the Flask, we use the function decorate @app.route to indicate that the function is
bound with the URL provided in the parameter of the route function.
Creating the basic route: In this case, we are binding the URL “/” which is the base URL for the
server with the function “index”, you can call it whatever you like but it makes more sense to call it
index here. The function simply returns something here it calls the function render_template. The
render_template finds the app by default in the templates folder. So, we just need to provide the name
of the template instead of the entire path to the template. The index function renders a template
index.html and hence we see the result in the browser.
Now, we need a way to actually link the template with a specific route or URL. This means whenever
the user goes to a specific URL then a specific template should be rendered or generated. Now, we
need to change the “server.py” with the following:
Python
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run()
Output:
We have imported the render_template function from the Flask module and added a route.
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey'
class MyForm(FlaskForm):
name = StringField('Name', validators=[InputRequired()])
password = PasswordField('Password', validators=[InputRequired()])
remember_me = BooleanField('Remember me')
salary = DecimalField('Salary', validators=[InputRequired()])
gender = RadioField('Gender', choices=[
('male', 'Male'), ('female', 'Female')])
country = SelectField('Country', choices=[('IN', 'India'), ('US', 'United States'),
('UK', 'United Kingdom')])
message = TextAreaField('Message', validators=[InputRequired()])
photo = FileField('Photo')
if __name__ == '__main__':
app.run()
HTML – index.html
<!DOCTYPE html>
<html>
<head>
<title>My Form</title>
</head>
<body>
<h1>My Form</h1>
<form method="post" action="/" enctype="multipart/form-data">
{{ form.csrf_token }}
<p>{{ form.name.label }} {{ form.name() }}</p>
<p>{{ form.password.label }} {{ form.password() }}</p>
<p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
<p>{{ form.salary.label }} {{ form.salary() }}</p>
<p>{{ form.gender.label }} {{ form.gender() }}</p>
<p>{{ form.country.label }} {{ form.country() }}</p>
<p>{{ form.message.label }} {{ form.message() }}</p>
<p>{{ form.photo.label }} {{ form.photo() }}</p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
In this example, we defined a MyForm class that inherits from FlaskForm and contains various fields
that we want to use in our application. The StringField, PasswordField, BooleanField, DecimalField,
RadioField, SelectField, TextAreaField, and FileField fields are defined with the appropriate
validators and options.
In the index function, we created an instance of MyForm and passed it to the index.html template file.
When the form is submitted, we validate it using the validate_on_submit method, and if it passes
validation, we retrieve the data from the form fields and display it in the browser. In order to encrypt
the password, we also used the generate_password_hash function and improved our form security.
Output:
Lecture-6 Build a base web page elements
Creating a Base Application
In your flask_blog directory, open a file named hello.py for editing, use nano or your favorite text
editor:
hello.py
This hello.py file will serve as a minimal example of how to handle HTTP requests. Inside it, you’ll
import the Flask object, and create a function that returns an HTTP response. Write the following
code inside hello.py:
flask_blog/hello.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello, World!'
In the preceding code block, you first import the Flask object from the flask package. You then use it
to create your Flask application instance with the name app. You pass the special variable __name__
that holds the name of the current Python module. It’s used to tell the instance where it’s located—
you need this because Flask sets up some paths behind the scenes.
Once you create the app instance, you use it to handle incoming web requests and send responses to
the user. @app.route is a decorator that turns a regular Python function into a Flask view function,
which converts the function’s return value into an HTTP response to be displayed by an HTTP client,
such as a web browser. You pass the value '/' to @app.route() to signify that this function will respond
to web requests for the URL /, which is the main URL.
The hello() view function returns the string 'Hello, World!' as a response.
export FLASK_APP=hello
Then run it in development mode with the FLASK_ENV environment variable:
export FLASK_ENV=development
Lastly, run the application using the flask run command:
flask run
Once the application is running the output will be something like this:
Open templates/base.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% block content %}
<h1>{% block title %} Welcome to FlaskBlog {% endblock %}</h1>
{% endblock %}
App.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
OUTPUT
Keywords
• Flask, Jinja Template, routing, redirecting, SQLite, SMTP, Deployment, HTTP Method
Sample Questions
Remember
1. Explain features of flask
2. Features of Flask
3. Jinja Template
Understand
1. Explain about database connectivity in flask
2. Explain Routing concept
Apply
Mind Map
Student Summary
At the end of this session, the facilitator (Teacher) shall randomly pic-up few students to
summarize the deliverables
Reading Materials