modern web application framework - python, sql alchemy, jinja2

70
UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask Devert Alexandre December 29, 2012 — Slide 1/62

Upload: hakhuong

Post on 02-Jan-2017

257 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Modern Web Application FrameworkPython, SQL Alchemy, Jinja2 & Flask

Devert Alexandre

December 29, 2012 — Slide 1/62

Page 2: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 2/62

Page 3: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Model-View-Controller

Most of the modern web development frameworks follow theModel-View-Controller model (MVC model)

• The model : representation of data. Usually, have astrong relation with the database

• The views : what is shown to the user. Can be any kindof user interface, usually HTML pages with Javascript.

• The controls : what operation are done on the data.

It’s a rather convenient way to design software projectsinvolving user interfaces presenting and manipulating data.

Devert Alexandre — Modern Web Application Framework — Slide 3/62

Page 4: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Model-View-Controller

Application

Model Viewupdates

User

showsController manipulates

uses

Devert Alexandre — Modern Web Application Framework — Slide 4/62

Page 5: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Model-View-Controller

Example for Model-View-Controller : an online managementgame

• The rule of the game, updating the state of each player⇒ the model

• The HTML pages, showing the various screen of thegame ⇒ the views

• The methods called when a user click on the screen ⇒the controllers

Devert Alexandre — Modern Web Application Framework — Slide 5/62

Page 6: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Model-View-Controller

Example for Model-View-Controller : an online shop

• The list of products, the payment rules, delivery orders⇒ the model

• The HTML pages, showing the various screen of theshop ⇒ the views

• The methods for payment, order, shopping cart ⇒ thecontrollers

Devert Alexandre — Modern Web Application Framework — Slide 6/62

Page 7: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Model-View-Controller

Model-View-Controller also helps to organize the work

• Some work on the views ⇒ graphic designers, HTML,javascript

• Some work on the model ⇒ database, softwarearchitecture

• Some work on the controls ⇒ rather low-level and/orspecialized code

• Some work on writing unit tests for at least the modeland the views

Devert Alexandre — Modern Web Application Framework — Slide 7/62

Page 8: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 8/62

Page 9: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Web application with script language

Why using a scripting language for a web application ?

• More adapted language to paste together variouscomponents (database, rendering, routing, . . . )

• Make its easier to release early & often

• Easier to maintain & modify

• Speed far enough for many use case

Devert Alexandre — Modern Web Application Framework — Slide 9/62

Page 10: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Web application with script language

Why not PHP, or PHP framework ?

• Designed to make simple web pages, not large webapplications

• Awfully designed programming language

• very inconsistent libraries

• very little help for debugging

• many security issues

• many better alternatives

Detailed explanation herehttp://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design

Devert Alexandre — Modern Web Application Framework — Slide 10/62

Page 11: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Web application with script language

Why not using Java/JSP/JBoss/Apache/Hibernate/Spring ?

• Even simple changes requires lots of coding

• Big changes takes a lot of planning

• Edit/Compile/Run takes more ressource

• General speed of development much reduced

• Working without a big fat IDE is tedious

But you can use those all this with a script-like language :Grails and Groovy

Devert Alexandre — Modern Web Application Framework — Slide 11/62

Page 12: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Flask

I am going to introduce the framework Flask

• It is small : quick to learn and master

• It is complete : you can use to do serious apps

• It is lean : a shell and a text editor are enough, no needfor an IDE to be efficient with it

• It is very well documented

The same ideas can be found in most web developmentframeworks.

Devert Alexandre — Modern Web Application Framework — Slide 12/62

Page 13: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Flask

Flask is a nice glue around existing tools

• Python ⇒ programming language

• SQL Alchemy ⇒ database

• Jinja2 ⇒ HTML template system

• Werkzeug ⇒ WSCGI handling (CGI, but better)

Devert Alexandre — Modern Web Application Framework — Slide 13/62

Page 14: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 14/62

Page 15: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Hello, world !

A minimal Flask application

from f l a s k impor t F l a s kapp = F l a s k ( name )

@app . r ou t e ( ’ / ’ )d e f h e l l o ( ) :

r e t u r n ’ He l l o World ! ’

i f name == ’ ma i n ’ :app . run ( )

Run this, and open your web browser athttp://127.0.0.1:5000

Devert Alexandre — Modern Web Application Framework — Slide 15/62

Page 16: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Hello, world !You will see this

Devert Alexandre — Modern Web Application Framework — Slide 16/62

Page 17: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Hello, world !

This creates an application instance and run it

from f l a s k impor t F l a s kapp = F l a s k ( name )

i f name == ’ ma i n ’ :app . run ( )

Devert Alexandre — Modern Web Application Framework — Slide 17/62

Page 18: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Hello, world !

This adds the hello method to the application instance

@app . r ou t e ( ’ / ’ )d e f h e l l o ( ) :

r e t u r n ’ He l l o World ! ’

• hello() will be called every time the address / isrequested

• hello() returns the text data for the web browser

Devert Alexandre — Modern Web Application Framework — Slide 18/62

Page 19: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Debugging

Triggering the debug mode is easy

from f l a s k impor t F l a s kapp = F l a s k ( name )

@app . r ou t e ( ’ / ’ )d e f h e l l o ( ) :

r e t u r n ’ He l l o World ! ’

i f name == ’ ma i n ’ :app . run ( debug = True )

In debug mode, you can edit the code while the server runs :it will restart !

Devert Alexandre — Modern Web Application Framework — Slide 19/62

Page 20: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

DebuggingThe debug mode will also helps a lot to point where theproblem is

Devert Alexandre — Modern Web Application Framework — Slide 20/62

Page 21: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 21/62

Page 22: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

When an URL is requested, Flask will look for itscorresponding function.

from f l a s k impor t F l a s kapp = F l a s k ( name )

@app . r ou t e ( ’ / ’ )d e f i nd e x ( ) :

r e t u r n ’ I ndex Page ’

@app . r ou t e ( ’ /welcome ’ )de f h e l l o ( ) :

r e t u r n ’ He l l o World ’

i f name == ’ ma i n ’ :app . run ( )

One function return text data. It can be HTM, XML, JSON,etc.

Devert Alexandre — Modern Web Application Framework — Slide 22/62

Page 23: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

You can defines URL with parameters

@app . r ou t e ( ’ / show name/<name>’ )d e f p r i n t name (name ) :

r e t u r n ’ He l l o , %s ! ’ % name

It gives a nice way, intuitive way to define ressources on awebsite.

Devert Alexandre — Modern Web Application Framework — Slide 23/62

Page 24: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

You can make URL parameters optional

@app . r ou t e ( ’ / h e l l o / ’ )@app . r ou t e ( ’ / h e l l o/<name>’ )d e f h e l l o ( name = None ) :

i f name i s None :r e t u r n ’A ho r s e w i th no name ’

e l s e :r e t u r n ’A ho r s e named %s ’ % name

Devert Alexandre — Modern Web Application Framework — Slide 24/62

Page 25: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

You can enforce the type of a parameter

@app . r ou t e ( ’ /team/< i n t : team id>’ )d e f show team ( team id ) :

r e t u r n ’ team #%d ’ % team id

Flask will check the type for you

Devert Alexandre — Modern Web Application Framework — Slide 25/62

Page 26: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

You can translate function names to URL with url for()

@app . r ou t e ( ’ / ’ )d e f welcome ( ) :

r e t u r n ’ He l l o World ! ’

@app . r ou t e ( ’ / t e s t ’ )d e f t e s t ( ) :

name = ’ welcome ’r e t u r n ’ u r l f o r ”%s ” = ”%s ” ’ % (name , u r l f o r ( name ) )

Especially convenient when you might have to change theURL naming scheme

Devert Alexandre — Modern Web Application Framework — Slide 26/62

Page 27: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Function / URL mapping

url for() also works for URL with parameters

@app . r ou t e ( ’ / show name/<name>’ )d e f p r i n t name (name ) :

r e t u r n ’ He l l o , %s ! ’ % name

@app . r ou t e ( ’ / t e s t ’ )d e f t e s t ( ) :

func name , user name = ’ p r i n t name ’ , ’ A lex ’r e t u r n ’ u r l f o r ”%s ” = ”%s ” ’ % ( func name , u r l f o r ( func name , name = user name ) )

Devert Alexandre — Modern Web Application Framework — Slide 27/62

Page 28: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Catching HTTP errors

The HTTP protocol defines several status codes.

status code meaning

400 Bad Request401 Unauthorized402 Payment Required403 Forbidden404 Not Found500 Internal Server Error501 Not Implemented503 Service Unavailable

Devert Alexandre — Modern Web Application Framework — Slide 28/62

Page 29: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Catching HTTP errors

Using @errorhandler, you can catch such errors

@app . e r r o r h a n d l e r (403)de f p a g e f o r b i d d e n ( e r r o r ) :

p r i n t ’Hey ! You a r e not a l l owed to a c c e s s t h i s ! ’

@app . e r r o r h a n d l e r (404)de f page no t f ound ( e r r o r ) :

p r i n t ’Ho no ! The r e s s o u r c e you want to a c c e s s does not e x i s t : ( ’

Devert Alexandre — Modern Web Application Framework — Slide 29/62

Page 30: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Throwing HTTP errors

It is also possible to throw HTTP errors with abort

@app . r ou t e ( ’ / s h ow a c c oun t i n f o s ’ )d e f s h ow a c c oun t i n f o s ( ) :

i f not u s e r . l o g g e d i n :abo r t (401)

# Do t h i n g s . . .

For instance, an error 401 to deny access to ressources

Devert Alexandre — Modern Web Application Framework — Slide 30/62

Page 31: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 31/62

Page 32: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

The need for templates

Generating HTML directly with code

• Easy to make very hard to read code

• Mix-up the control code with the view code

Text template system is a convenient and common way toseparade the view code from the remaining code

Devert Alexandre — Modern Web Application Framework — Slide 32/62

Page 33: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

The need for templates

Flask uses Jinja2 as template system. There are many otherstemplate system

• Mako, for Python (if you ask me, it’s better than Jinja2)

• JSP, for Java, THE standard for Java. Allow to mixJava & HTML.

• ASP, for Microsoft products. Allow to mix VBScript &HTML.

• XSLT is a template system based on XML. Plateformindepedent but not very convenient in practice.

• Maybe 10 different for every language you can think of

Devert Alexandre — Modern Web Application Framework — Slide 33/62

Page 34: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

The function render template takes a path to an HTML file,and arbitrary parameters

from f l a s k impor t F lask , r e n d e r t emp l a t eapp = F l a s k ( name )

@app . r ou t e ( ’ / h e l l o / ’ )@app . r ou t e ( ’ / h e l l o/<name>’ )d e f h e l l o ( name = None ) :

r e t u r n r e n d e r t emp l a t e ( ’ h e l l o . html ’ , name = name)

i f name == ’ ma i n ’ :app . run ( )

What will be returned will the content of hello.html

Devert Alexandre — Modern Web Application Framework — Slide 34/62

Page 35: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

The HTML file hello.html

<! doctype html><html>

<head>< t i t l e>The web s i t e t ha t s a y s He l l o to you</ t i t l e>

</head><body>{% i f name %}<h1>He l l o , {{ name }} !</h1>{% e l s e %}<h1>He l l o , t h i n g wi th no name !</h1>{% end i f %}

</body></html>

It’s no ordinary HTML ⇒ there are instruction mixed in !

Devert Alexandre — Modern Web Application Framework — Slide 35/62

Page 36: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

The HTML file hello.html

<! doctype html><html>

<head>< t i t l e>The web s i t e t ha t s a y s He l l o to you</ t i t l e>

</head><body>{% i f name %}<h1>He l l o , {{ name }} !</h1>{% e l s e %}<h1>He l l o , t h i n g wi th no name !</h1>{% end i f %}

</body></html>

hello.html is processed to generate the HTML to send to auser. Here, we use the name variable, passed as a parameterof render template

Devert Alexandre — Modern Web Application Framework — Slide 35/62

Page 37: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

The HTML file hello.html

<! doctype html><html>

<head>< t i t l e>The web s i t e t ha t s a y s He l l o to you</ t i t l e>

</head><body>{% i f name %}<h1>He l l o , {{ name }} !</h1>{% e l s e %}<h1>He l l o , t h i n g wi th no name !</h1>{% end i f %}

</body></html>

Variables values can be rendered to text with {{ }}

Devert Alexandre — Modern Web Application Framework — Slide 35/62

Page 38: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

The HTML file hello.html

<! doctype html><html>

<head>< t i t l e>The web s i t e t ha t s a y s He l l o to you</ t i t l e>

</head><body>{% i f name %}<h1>He l l o , {{ name }} !</h1>{% e l s e %}<h1>He l l o , t h i n g wi th no name !</h1>{% end i f %}

</body></html>

Blocks of code are put between {% %}

Devert Alexandre — Modern Web Application Framework — Slide 35/62

Page 39: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Basic template rendering

Flask assumes that all your templates will be in a templatedirectory, relative to your script

|− t emp l a t e s| || |− h e l l o . html||− t e s t . py

Devert Alexandre — Modern Web Application Framework — Slide 36/62

Page 40: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Using ressources

If you wish to use other file ressources, like pictures or CSSfiles, you can put them in directory named static

|− t emp l a t e s| || |− h e l l o . html||− s t a t i c| || |− s t y l e . c s s||− t e s t . py

Those resource are not dynamic, not generated on the fly likethe HTML code, hence the name ”static”

Devert Alexandre — Modern Web Application Framework — Slide 37/62

Page 41: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Using ressources

Then, to use those ressources, you can again use url for

<! doctype html><html>

<head>< t i t l e>The web s i t e t ha t s a y s He l l o to you</ t i t l e>< l i n k r e l=s t y l e s h e e t type=t e x t / c s s

h r e f=”{{ u r l f o r ( ’ s t a t i c ’ , f i l e n ame=’ s t y l e . c s s ’ ) }}”></head><body>{% i f name %}<h1>He l l o , {{ name }} !</h1>{% e l s e %}<h1>He l l o , t h i n g wi th no name !</h1>{% end i f %}

</body></html>

Devert Alexandre — Modern Web Application Framework — Slide 38/62

Page 42: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

On a typical website, different views follow a similar design

Devert Alexandre — Modern Web Application Framework — Slide 39/62

Page 43: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

On a typical website, different views follow a similar design

Devert Alexandre — Modern Web Application Framework — Slide 39/62

Page 44: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

On a typical website, different views follow a similar design

Devert Alexandre — Modern Web Application Framework — Slide 39/62

Page 45: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

On a typical website, different views follow a similar design

Devert Alexandre — Modern Web Application Framework — Slide 39/62

Page 46: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

Jinja2 provides a simple way to share a common templateand specialize it : template inheritance

{% extend s ” base . html ” %}

{% block con t en t %}{% i f name %}<h2>He l l o , {{ name }} !</h2>{% e l s e %}<h2>He l l o , t h i n g wi th no name !</h2>{% end i f %}

{% endb lock %}

hello.html extends base.html

Devert Alexandre — Modern Web Application Framework — Slide 40/62

Page 47: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

Jinja2 provides a simple way to share a common templateand specialize it : template inheritance

{% extend s ” base . html ” %}

{% block con t en t %}{% i f name %}<h2>Goodbye , {{ name }} !</h2>{% e l s e %}<h2>Goodbye , t h i n g wi th no name !</h2>{% end i f %}

{% endb lock %}

goodbye.html extends base.html

Devert Alexandre — Modern Web Application Framework — Slide 40/62

Page 48: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritanceAnd base.html look like this

<!DOCTYPE HTML PUBLIC ”−//W3C//DTD HTML 4.01//EN”><html l ang=”en”>

<head>< t i t l e>Sa l u t e . com , the web s i t e t ha t s a l u t e s you</ t i t l e>< l i n k r e l=s t y l e s h e e t type=t e x t / c s s h r e f=”{{ u r l f o r ( ’ s t a t i c ’ , f i l e n ame=’ s t y l e . c s s ’ ) }}”>

</head><body>

<d i v i d=” c o n t a i n e r ”><d i v i d=” heade r ”>

<h1>Sa l u t e . com</h1><p>The web s i t e t ha t s a l u t e s you</p>

</ d i v>

<d i v i d=” con ten t ”>{% block con t en t %}{% endb lock %}

</ d i v></ d i v>

<d i v i d=” f o o t e r ”><h2>Sa l u t e . com</h2><p>S i t e d e s i g n &amp ; c o p y r i g h t &copy ; A l exand re Dever t</p>

</ d i v></body>

</html>

Devert Alexandre — Modern Web Application Framework — Slide 41/62

Page 49: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

On the Python side, hello.html and goodbye.html are justnormal HTML pages, nothing special to do

@app . r ou t e ( ’ / h e l l o / ’ )@app . r ou t e ( ’ / h e l l o/<name>’ )d e f h e l l o ( name = None ) :

r e t u r n r e n d e r t emp l a t e ( ’ h e l l o . html ’ , name = name)

@app . r ou t e ( ’ / goodbye / ’ )@app . r ou t e ( ’ / goodbye/<name>’ )d e f goodbye (name = None ) :

r e t u r n r e n d e r t emp l a t e ( ’ goodbye . html ’ , name = name)

Devert Alexandre — Modern Web Application Framework — Slide 42/62

Page 50: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template inheritance

In this exemple, extending base.html provides

• A common title

• Includes common ressources (css, javascript, etc.)

• A common header

• A common footer

• The specialized part goes in the ”content” block.

Coherent look, code reusage, and clean separation !

Devert Alexandre — Modern Web Application Framework — Slide 43/62

Page 51: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template macros

On a website, the same user interface elements are oftenre-used

Devert Alexandre — Modern Web Application Framework — Slide 44/62

Page 52: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template macros

On a website, the same user interface elements are oftenre-used

Devert Alexandre — Modern Web Application Framework — Slide 44/62

Page 53: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template macros

We can define reusable HTML bits of codes.

{%− macro r e n d e r p a n e l ( t i t l e , s t y l e=” l e f t ” ) %}<d i v c l a s s=” pane l ”>

<h1 c l a s s=”{{ s t y l e }}”>{{ t i t l e }}</h1><d i v c l a s s=” pane l−con t en t ”>

<d i v c l a s s=”{{ s t y l e }}”>{{ c a l l e r ( ) }}

</ d i v></ d i v>

</ d i v>{%− endmacro %}

This define a box, containing whatever caller() will put in it,and with a title. We put this in ui.html

Devert Alexandre — Modern Web Application Framework — Slide 45/62

Page 54: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template macrosNow, we can create lots of boxes.

{% extend s ” base . html ” %}{% impor t ” u i . html ” as u i %}

{% block con t en t %}<d i v c l a s s=” th ree−columns−l a y o u t ”>

<d i v c l a s s=” l e f t−column”>{% c a l l u i . r e n d e r p a n e l ( ”Lorem ipsum” , ” l e f t ” ) %}. . . b l a b l a . . .{% en d c a l l %}

{% c a l l u i . r e n d e r p a n e l ( ”Lorem ipsum” , ” l e f t ” ) %}. . . b l a b l a . . .{% en d c a l l %}

</ d i v><d i v c l a s s=” r i g h t−column”>{% c a l l u i . r e n d e r p a n e l ( ” H i s t o r y ” , ” l e f t ” ) %}. . . b l a b l a . . .{% en d c a l l %}{% c a l l u i . r e n d e r p a n e l ( ”Now i s the t ime f o r a l l good men” , ” l e f t ” ) %}. . . b l a b l a . . .{% en d c a l l %}

</ d i v></ d i v>{% endb lock %}

No need to copy paste the same HTML code around !Devert Alexandre — Modern Web Application Framework — Slide 46/62

Page 55: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template macros

To use a macro, first import the file that contains that macro

{% impor t ” u i . html ” as u i %}

Then you can call the macro

{% c a l l u i . r e n d e r p a n e l ( ”My T i t l e Here ” , ” l e f t ” ) %}. . . b l a b l a . . .{% en d c a l l %}

What is between call and endcall could be any valid HTMLcode. It will be placed in place of caller in the macrodefinition.

Devert Alexandre — Modern Web Application Framework — Slide 47/62

Page 56: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

Jinja templates use their own language, more or lessPython-like.

• It tries to imitate Python

• But it is not Python

Why not having full power of Python in a template ?

Devert Alexandre — Modern Web Application Framework — Slide 48/62

Page 57: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

Jinja provides a limited language because

• It’s a view. No business code here. Just HTMLgeneration.

• It’s a page that might be served for many differentusers. Should be fast.

Devert Alexandre — Modern Web Application Framework — Slide 49/62

Page 58: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

The if block works like Python

{% i f show adve r t i s emen t %}<h1>Buy Drunk Panda , the b e s t bee r i n Suzhou !</h1>{% end i f %}

Devert Alexandre — Modern Web Application Framework — Slide 50/62

Page 59: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

An optional else block works can be used

{% i f show adve r t i s emen t %}<h1>Buy Drunk Panda , the b e s t bee r i n Suzhou !</h1>{% e l s e %}Do not buy any th i ng{% end i f %}

Devert Alexandre — Modern Web Application Framework — Slide 51/62

Page 60: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

An even elif blocks are available

{% i f s h ow be e r a d v e r t i s emen t %}<h1>Buy Drunk Panda , the b e s t bee r i n Suzhou !</h1>{% e l i f s h ow p i z z a a d v e r t i s emen t %}<h1>Buy P i z za Hut , the wors t p i z z a s e v e r !</h1>{% e l s e %}Do not buy any th i ng{% end i f %}

Devert Alexandre — Modern Web Application Framework — Slide 52/62

Page 61: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

The Jinja for loop works like the Python one

{% f o r i tem i n n a v i g a t i o n %}< l i>

<a h r e f=”{{ i t em . h r e f }}”>{{ i t em . c ap t i o n }}</a></ l i>{% end f o r %}

Note that

• navigation is a sequence, passed to the template

• item is one item of the sequence

• loop code is between {% for %} and {% endfor %}

Devert Alexandre — Modern Web Application Framework — Slide 53/62

Page 62: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

Jinja provides a loop object that can be called inside a forloop

{% f o r i tem i n n a v i g a t i o n %}< l i>

<a h r e f=”{{ i t em . h r e f }}”>{{ l oop . i nd e x}} {{ i t em . c ap t i o n }}</a></ l i>{% end f o r %}

Devert Alexandre — Modern Web Application Framework — Slide 54/62

Page 63: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

This loop object provides some useful informations about thecurrent item of the loop

loop variable meaning

loop.index Current index (1-indexed)

loop.index0 Current index (0-indexed)

loop.revindex Current index, reversed order (1-indexed)

loop.revindex0 Current index, reversed order (0-indexed)

loop.last True if last item

loop.first True if first item

Devert Alexandre — Modern Web Application Framework — Slide 55/62

Page 64: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

You can filter the for loop, as in Python

{% f o r u s e r i n u s e r l i s t i f not u s e r . i s h i d d e n %}< l i>{{ u s e r . name }}

</ l i>{% end f o r %}

Devert Alexandre — Modern Web Application Framework — Slide 56/62

Page 65: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Template language

If the sequence you iterate turns out to be empty, you cancatch this case with an else block

{% f o r u s e r i n u s e r l i s t i f not u s e r . i s h i d d e n %}< l i>{{ u s e r . name }}

</ l i>{% e l s e %}

No u s e r s found !{% end f o r %}

Devert Alexandre — Modern Web Application Framework — Slide 57/62

Page 66: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Table of Contents

1 Model-View-Controller

2 Flask

3 First steps

4 Routing

5 TemplatesBasic template renderingUsing ressourcesTemplate inheritanceTemplate macrosTemplate language

6 Requests

Devert Alexandre — Modern Web Application Framework — Slide 58/62

Page 67: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Requests

We can send data (HTML, JSON, XML, any kind of text),but we also need to receive data

• passwords

• checkboxes

• values

• . . .

Devert Alexandre — Modern Web Application Framework — Slide 59/62

Page 68: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Requests

The HTTP protocol defines different kind of requests

• GET ⇒ request to send data

• POST ⇒ request to accept data

So far, we only handled GET requests : sending HTML data.

Devert Alexandre — Modern Web Application Framework — Slide 60/62

Page 69: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Requests

We can also handle POST requests, like this

from f l a s k impor t r e q u e s t

@app . r ou t e ( ’ / l o g i n ’ , methods = [ ’GET ’ , ’POST ’ ] )de f l o g i n ( ) :

# GET r e qu e s ti f r e q u e s t . method == ’GET ’ :

r e t u r n r e n d e r t emp l a t e ( ’ l o g i n . html ’ )# POST REQUESTe l s e :

ema i l = r e qu e s t . form [ ’ ema i l ’ ]password = r e qu e s t . form [ ’ password ’ ]

# Check ema i l & password# TODO

r e t u r n r e n d e r t emp l a t e ( ’ welcome . html ’ )

Devert Alexandre — Modern Web Application Framework — Slide 61/62

Page 70: Modern Web Application Framework - Python, SQL Alchemy, Jinja2

UNIVERSITY OF SCIENCE AND TECHNOLOGY OF CHINA SCHOOL OF SOFTWARE ENGINEERING OF USTC

Requests

The request object hold the information sent to the server

<form name=” l o g i n ” method=” pos t ” a c t i o n=”{{ u r l f o r ( ’ l o g i n ’ ) }}”>< l a b e l>Emai l</ l a b e l><i n pu t type=” t e x t ” name=” ema i l ” maxlength=”254”/>

< l a b e l>Password</ l a b e l><i n pu t type=”password ” name=”password ”/>

<button type=” submit ”>Ente r</ button></ form>

Devert Alexandre — Modern Web Application Framework — Slide 62/62