0% found this document useful (0 votes)
30 views14 pages

GMR Institute of Technology Rajam, AP: 1. Objective

javasctipt

Uploaded by

rahulnakka74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views14 pages

GMR Institute of Technology Rajam, AP: 1. Objective

javasctipt

Uploaded by

rahulnakka74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

GMR Institute of Technology GMRIT/ADM/F-44

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.

2. Intended Learning Outcomes (ILOs)

At the end of this session the students will able to:

A. Develop falsk backend web pages.


B. Able to create render website pages
C. Able to sending mail
D. Able use database operations

3. 2D Mapping of ILOs with Knowledge Dimension and Cognitive Learning


Levels of RBT

Cognitive Learning Levels (2D)


Knowledge
Remember Understand Apply Analyze Evaluate Create
Dimension (1D)
Factual A
Conceptual B
Procedural C
Meta Cognitive D
4. Teaching Methodology

Chalk & Board, Visual Presentation

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.

Install virtualenv for development environment


virtualenv is a virtual Python environment builder. It helps a user to create multiple Python
environments side-by-side. Thereby, it can avoid compatibility issues between the different versions
of the libraries.
The following command installs virtualenv.
pip install virtualenv
This command needs administrator privileges. Add sudo before pip on Linux/Mac OS. If you are on
Windows, log in as Administrator. On Ubuntu virtualenv may be installed using its package manager.
Sudo apt-get install virtualenv
Once installed, new virtual environment is created in a folder.
mkdir newproj
cd newproj
virtualenv venv
To activate corresponding environment, on Linux/OS X, use the following:
venv/bin/activate
On Windows, following can be used:
venv\scripts\activate
We are now ready to install Flask in this environment.
pip install Flask

Lecture-2: Redirecting web pages


Flask is a backend server that is built entirely using Python. It is a framework that consists of Python
packages and modules. It is lightweight which makes developing backend applications quicker with
its features. In this article, we will learn to redirect a URL in the Flask web application.

Redirect to a URL in Flask


A redirect is used in the Flask class to send the user to a particular URL with the status code.
conversely, this status code additionally identifies the issue. When we access a website, our browser
sends a request to the server, and the server replies with what is known as the HTTP status code,
which is a three-digit number.

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.

The different types of HTTP codes are:


Code Status
300 Multiple_choices
301 Moved_permanently
302 Found
303 See_other
304 Not_modified
305 Use_proxy
306 Reserved
307 Temporary_redirect

To Redirect To Url in Flask


In this example, we have created a sample flask application app.py. It has two routes, One is the base
route \ and another is \helloworld route. Here when a user hits the base URL \ (root) it will redirect to
\helloworld.

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

Lecture-3: Python Web Template Design


The Jinja2 Template Engine
In its simplest form, a Jinja2 template is a file that contains the text of a response. Jinja2 template that
matches the response of the index() view function
templates/index.html: Jinja2 template
<h1>Hello World!</h1>
The response returned by view function user() of a dynamic component, which is represented by a
variable. The template that implements this response.
templates/user.html: Jinja2 template
<h1>Hello, {{ name }}!</h1>
Rendering Templates
By default Flask looks for templates in a templates subfolder located inside the application folder. For
the next version of hello.py, you need to store the templates defined earlier in a new templates folder
as index.html and user.html. The view functions in the application need to be modified to render these
templates
hello.py: Rendering a template
from flask import Flask, render_template
# ...
@app.route('/index')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)

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 }}

Jinja2 variable filters

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.

Lecture-4 Rendering templates Importance


Rendering a Template in a Flask Application
Setting up Flask is quite easy. We can use a virtual environment to create an isolated environment for
our project and then install the Python packages in that environment. After that, we set up the
environment variables for running Flask on the local machine. This tutorial assumes that you have a
Python environment configured, if not please follow through for setting up Python and pip on your
system. Once you are done, you are ready to develop Flask applications.

Flask For Windows:


set FLASK_APP=server

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.

Lecture 5 – Interaction with form groups


Flask - app.py
# Importing Libraries..
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms import DecimalField, RadioField, SelectField, TextAreaField, FileField
from wtforms.validators import InputRequired
from werkzeug.security import generate_password_hash

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')

@app.route('/', methods=['GET', 'POST'])


def index():
form = MyForm()
if form.validate_on_submit():
name = form.name.data
password = form.password.data
remember_me = form.remember_me.data
salary = form.salary.data
gender = form.gender.data
country = form.country.data
message = form.message.data
photo = form.photo.data.filename
return f'Name: {name} < br > Password: {generate_password_hash(password)}
<br > Remember me: {remember_me} < br > Salary: {salary} < br > Gender: {gender}
<br > Country: {country} < br > Message: {message} < br > Photo: {photo}'
return render_template('index.html', form=form)

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.

Save and close the file.


To run your web application, you’ll first tell Flask where to find the application (the hello.py file in
your case) with the FLASK_APP environment variable:

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">

<!-- Bootstrap CSS -->


<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">

<title>{% block title %} {% endblock %}</title>


</head>
<body>
<nav class="navbar navbar-expand-md navbar-light bg-light">
<a class="navbar-brand" href="{{ url_for('index')}}">FlaskBlog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</nav>
<div class="container">
{% block content %} {% endblock %}
</div>

<!-- Optional JavaScript -->


<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-
q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-
UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-
JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
</body>
</html>
Index.html
{% extends 'base.html' %}

{% 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

1. Design web page to implement the SMTP mailing


2. Deploying the flask webpage in real time

Stimulating Question (s)

Design a flask based Website and deploys in real time

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

Scope for Mini Project


Yes

You might also like