0% found this document useful (0 votes)
40 views

Flask

The document discusses building web applications in Python using Flask as a simple framework. It provides an overview of Flask, including that Flask is a lightweight WSGI web framework designed to make getting started quick. It can scale to complex applications. Flask wraps Werkzeug to handle WSGI details and Jinja2 to handle templates. The document demonstrates creating a basic Flask application with routes and rendering templates, and discusses using Jinja2 templating to separate HTML structure from variable content.

Uploaded by

Mohamed elfegane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Flask

The document discusses building web applications in Python using Flask as a simple framework. It provides an overview of Flask, including that Flask is a lightweight WSGI web framework designed to make getting started quick. It can scale to complex applications. Flask wraps Werkzeug to handle WSGI details and Jinja2 to handle templates. The document demonstrates creating a basic Flask application with routes and rendering templates, and discusses using Jinja2 templating to separate HTML structure from variable content.

Uploaded by

Mohamed elfegane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Building Web Applications

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Goal
● Create simple web applications in Python
● For interactive interfaces
● For server-side components

● Learn a simple framework – Start simple


● Extensible with modules

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Summary
● Flask

● Case studies
● First Flask basic application
● Jinja2 Templates
● User interaction

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Flask - what it is
● Flask is a lightweight WSGI web application framework. It is designed to make getting started
quick and easy, with the ability to scale up to complex applications. It began as a simple
wrapper around Werkzeug [1] and Jinja2 [2] and has become one of the most popular Python
web application frameworks.

● WSGI (pronounced whiskey) - The Web Server Gateway Interface is a simple calling
convention for web servers to forward requests to web
applications or frameworks written in the Python programming language

● Flask offers suggestions, but doesn't enforce any dependencies or project layout. It is up to
the developer to choose the tools and libraries they want to use. There are many extensions
provided by the community that make adding new functionality easy.

1. https://pypi.org/project/Werkzeug/
2. https://www.palletsprojects.com/p/jinja/
Pr. M. A. BELHAMRA Advanced Python 2022/2023
Werkzeug
● Werkzeug is a comprehensive WSGI web application library. It began as a
simple collection of various utilities for WSGI applications and has become
one of the most advanced WSGI utility libraries.
● Flask wraps Werkzeug, using it to handle the details of WSGI while
providing more structure and patterns for defining powerful applications.

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Jinja2

● Jinja2 is a full-featured template engine for Python.


● Flask wraps Jinja2, using it to handle templates.

{% extends "layout.html" %}
{% block body %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Flask installation
● Install Flask, Werkzeug and Jinja2 in a single step (system-wide installation)

$> sudo pip install Flask


$> …
$> …
$> Successfully installed Flask-1.1.0

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Flask applications
● One ‘Flask’ object represents the whole application

from flask import Flask


app = Flask(__name__)
## __name__ is the application name

● Running the application starts the web server (running until you kill it)

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

Pr. M. A. BELHAMRA Advanced Python 2022/2023


The web server
● By default, Flask runs a web server on:
● http://127.0.0.1:5000/
● Accessible by localhost, only
● Running on port 5000

● Can be customized with parameters to the .run method

# syntax: app.run(host=None, port=None, debug=None,


**options)
app.run(host='0.0.0.0', port=80) # public
app.run(debug=True) # for development

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Web pages
● Each page is implemented by a method:

@app.route('/')
def index():
return "Hello, web world!"

● Must specify
● The (local) URL at which the page will be visible: '/' in the @app.route
decorator
● The name of the page: index
● The (HTML) content of the page: return statement
Pr. M. A. BELHAMRA Advanced Python 2022/2023
Case study 1: First Flask Application
Route: / Route: /slides

Softare Applications Slides


2020/2021 - Introduction
- What is Software?
This is the web page of the course

The slides are available here.


Back to home.

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Solution: HTML
<html>

<h1>Software Applications 2020/2021</h1>


<p>This is the web page of the course</p>
Route: / <p>The slides are available <a href="slides">here</a>.</
p>

</html>

<html>
<head>
<title>SA 2020/2021</title>
</head>
<body>
<h1>Slides</h1>
Route: /slides <ul>
<li>Introduction</li>
<li>What is Software?</li>
</ul>
<p>Back to <a href="/">home</a>.</p>
</body>
</html>

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Solution: Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
return """<html><head><title>SA 2020/2021</title></head><body><h1>Software Applications
2019/2020
</h1><p>This is the web page
of the course</p><p>The slides are available <a href="slides">here</a>.</p></body></html>
"""

@app.route('/slides')
def slides():
return """<html><head><title>SA 2020/2021</title></head><body><h1>Slides</h1><ul>
<li>Introduction</li><li>What is Software?</li></ul><p>Back to <a href="/">home</a>.</
p></body>
</html>
"""
if __name__ == '__main__':
app.run()

Pr. M. A. BELHAMRA Advanced Python 2022/2023


HTML templating with Jinja2
● Embedding HTML in Python strings is
● Ugly
● Error prone
● Complex (i.e., must follow HTML escaping rules and Python quoting
rules)
● Did I say Ugly?

● Templating: separating the (fixed) structure of the HTML text (template) from
the variable parts (interpolated variables)
● Flask supports the Jinja2 templating engine

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Jinja2 basics
● Templates should be in the ./templates subfolder
● Templates are HTML files, with .html extension
● Templates can interpolate passed-by values:
● {{ parameter }}
● {{ expression }}
● Templates can include programming statements:
● {% statement %}
● Templates can access some implicit objects
● request, session
● Templates are processed when requested by the Flask page
return render_template(‘slides.html', name=name)

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Case study 2: revised solution with templating
from flask import Flask
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/slides')
def slides():
return render_template(‘slides.html’)

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

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Revised solution with templating: HTML

<html>
<head>
<title>SA 2020/2021</title>
Route: / </head>
<body>
Located in: templates/index.html <h1>Software Applications 2020/2021</h1>
<p>This is the web page of the course</p>
<p>The slides are available <a href="slides">here</a>.</p>
</body>
</html>

<html>
<head>
<title>SA 2020/2021</title>
</head>
<body>
Route: /slides <h1>Slides</h1>
Located in: templates/slides.html <ul>
<li>Introduction</li>
<li>What is Software?</li>
</ul>
<p>Back to <a href="/">home</a>.</p>
</body>
</html>

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Main Jinja2 {% statements %}
● {% for var in list %} ... {% endfor %}

● {% if condition %} ... {% elif cond %} ...


{% else %} ... {% endif %}

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Statements Vs. Expressions
● A {% statement %} controls the flow of execution in a template

http://jinja.pocoo.org/docs/dev/templates/#list-of-control- structures

● An {{ expression }} evalutates the variable (or the expression) and «prints»


the results in the HTML file

http://jinja.pocoo.org/docs/dev/templates/#expressions

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Route: /
Case study 3 Softare Applications
2020/2021
Route: / Route: /login This is the web page of the course
Softare Applications Softare Applications
Welcome name!
2020/2021 2020/2021
This is the web page of the course Your nane: name

Enter username [________] [Submit] Continue


The slides are available.

Logout

Route: /slides
Slides
- Introduction
- What is Software?

Back to home.
Pr. M. A. BELHAMRA Advanced Python 2022/2023
Querying request parameters
● All FORM variable are sent with the HTTP request

● Flask packs all FORM variables in the ‘request.form’ object (a dictionary)

● ‘request’ is a global implicit object, and must be imported

from flask import request

user = request.form['user']

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Using parameters in templates
● Specify name=value of all needed parameters in the render_template call
● Within the template, use the {{ name }} syntax
● Template parameters need not be the same as FORM parameters (they are
independent concepts, independent values)

myuser = 'Andrea'
Flask return render_template('index.html', user=myuser)

<p>Welcome {{ user }}.</p>


Template

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Remembering values
● Values in request.form expire immediately

● We may «remember» values for a longer time

● By storing them in «session» containers – Based on HTTP cookies


– Kept in memory in the web server
– Valid until browser disconnection or timeout, only
– http://flask.pocoo.org/docs/0.10/quickstart/#sessions

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Implementing sessions in Flask
● Sessions are automatically initialised and managed by Flask
● Session data is encrypted. For that we must define a secret key
● app.secret_key = 'softwareapplicationssecret'
● The ‘session’ object is a global shared dictionary that stores attribute-value
pairs

myuser = 'Andrea'
Flask session['user'] = myuser

<p>Welcome {{ session['user'] }}.</p>


Template

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Automatic redirects
● In some cases, a user action doesn’t need to generate a response page
– E.g., the Logout action needs to destroy the session, but will just bring you
to the normal ‘index’ page

● You may use a ‘redirect’ method to instruct the browser that the current
response is empty, and it must load the new page (HTTP 302)

return redirect('/index'))

Pr. M. A. BELHAMRA Advanced Python 2022/2023


Exercise solution
from flask import Flask, render_template, request, session, redirect

app = Flask(__name__)
app.secret_key = 'softwareapplicationssecret'

@app.route('/')
def index():
return render_template('index2.html')

@app.route('/slides')
def slides():
user = session['user']
topics = ["Introduction", "What is Software?"]
return render_template('slides2.html', user=user, slides=topics)

@app.route('/login', methods=['POST'])
def login():
user = request.form['user']
session['user'] = user
return render_template('welcome.html', user=user)

@app.route('/logout')
def logout():
del session['user']
return redirect('/')

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

Pr. M. A. BELHAMRA Advanced Python 2022/2023


HTML solution: index2.html
<html>
<head>
<title>SA 2020/2021</title>
</head>
<body>
<h1>Software Applications 2020/2021</h1>

<p>This is the web page of the course</p>

{% if session.user %}
<p>Welcome {{ session['user'] }}!</p>
<p><img src="static/{{ session['user'] }}.png" /></p>
Route: / <p><a href="logout">Logout</a></p>
Located in: templates/index2.html {% else %}
<p>
<form action="login" method='POST'>
Enter name: <input type='text' name='user'>
<input type='submit' value='Submit'>
</form>
</p>
{% endif %}

</body>
</html>

Pr. M. A. BELHAMRA Advanced Python 2022/2023


HTML solution: welcome.html

<html>
<head>
<title>SA 2020/2021</title>
</head>
Route: /login <body>
Located in: templates/welcome.html <h1>Welcome</h1>
<p>Welcome {{ user }}.</p>
<p><a href="/">Continue</a> </p>
</body>
</html>

Pr. M. A. BELHAMRA Advanced Python 2022/2023


HTML solution: slides2.html
<html>
<head>
<title>SA 2020/2021</title>
</head>
<body>
<h1>Slides</h1>
<ul>
Route: /
Located in: templates/slides2.html {% for topic in slides %}
<li> {{ topic }} </li>
{% endfor %}

</ul>
<p>Back to <a href="/">home</a>.</p>
</body>
</html>

Pr. M. A. BELHAMRA Advanced Python 2022/2023

You might also like