26
Module 17 Web development with Flesk and Jinja Dr Diarmuid O'Briain

Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Module 17Web development with

Flesk and Jinja

Dr Diarmuid O'Briain

Page 2: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-2 Python programming

This page is intentionally blank

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 3: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-3

Table of Contents

1. Introduction..............................................................................................................................5

2. Dependencies.........................................................................................................................5

3. Install flask...............................................................................................................................5

3.1 Create a virtual environment......................................................................................................5

3.2 Hello World...................................................................................................................................7

4. Jinja2.....................................................................................................................................10

4.1 Jinja2 Template Inheritance....................................................................................................15

5. Web-services RESTful API..................................................................................................19

5.1 Run the server...........................................................................................................................19

5.2 Testing the server.....................................................................................................................19

6. Running in production..........................................................................................................23

7. Exercise.................................................................................................................................24

Illustration IndexIllustration 1: Flask - hello world program...................................................................................7

Illustration 2: Flask - hello world...................................................................................................9

Illustration 3: Simple Jinja2 template........................................................................................12

Illustration 4: Simple jinja2 application......................................................................................13

Illustration 5: Flask and Jinja2 webpage rendered..................................................................14

Illustration 6: Debugging Jinja2 and Flask................................................................................14

Illustration 7: Jinja2 base template............................................................................................15

Illustration 8: Jinja child template..............................................................................................16

Illustration 9: Jinja and Flask output demonstrating inheritance.............................................18

Illustration 10: Fibonacci RESTful API......................................................................................21

Illustration 11: RESTer URL browser in Mozilla.......................................................................22

Illustration 12: waitress server...................................................................................................23

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 4: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-4 Python programming

This page is intentionally blank

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 5: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-5

1. Introduction

Flask is a micro web framework written in python. It is classified as a micro-frameworkbecause it does not require particular tools or libraries.

2. Dependencies

When installing Flask these distributions will be installed automatically.

• Werkzeug implements WSGI, the standard Python interface betweenapplications and servers.

• Jinja is a template language that renders the pages your application serves.

• MarkupSafe comes with Jinja. It escapes untrusted input when renderingtemplates to avoid injection attacks.

• ItsDangerous securely signs data to ensure its integrity. This is used to protectFlask’s session cookie.

• Click is a framework for writing command line applications. It provides the flaskcommand and allows adding custom management commands.

These distributions will not be installed automatically but Flask will detect and use themif installed.

• Blinker provides support for Signals.

• SimpleJSON is a fast JSON implementation that is compatible with Python’sjson module. It is preferred for JSON operations if it is installed.

• python-dotenv enables support for loading environment variables from .envfiles when running flask commands.

3. Install flask

Install the python3 virtual environment, which serves to manage the dependencies forprojects, both in development and in production. Then install Flask and itsdependencies.

$ sudo apt-get install python3-venv

3.1 Create a virtual environment

~$ python3 -m venv </path/to/new/virtual/environment>

Running this command creates the target directory (creating any parent directories thatdon’t exist already) and places a pyvenv.cfg file in it with a home key pointing to thepython installation from which the command was run. It also creates a bin subdirectorycontaining a copy of the python binary. It also creates a lib/pythonX.Y/site-packagessubdirectory. If an existing directory is specified, it will be re-used.

Note: to update the virtual environment use the --upgrade switch.

~$ python3 -m venv --upgrade </path/to/new/virtual/environment>

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 6: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-6 Python programming

Create a virtual environment.

~$ python3 -m venv ./python3_flask

Here is a view of the environment created (some detail removed).

$ tree python3_flask .├── bin│ ├── activate│ ├── activate.csh│ ├── activate.fish│ ├── easy_install│ ├── easy_install-3.7│ ├── pip│ ├── pip3│ ├── pip3.7│ ├── python -> python3│ └── python3 -> /usr/bin/python3├── include├── lib│ └── python3.7│ └── site-packages├── lib64 -> lib├── pyvenv.cfg└── share └── python-wheels

48 directories, 345 files

Activate the virtual environment.

~$ cd python3_flask~/python3_flask$ . bin/activate~/python3_flask$

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 7: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-7

Install the required packages. Create a requirements.txt file which includes therequirements.

~/python3_flask$ cat requirements.txtblinker==1.4Flask==1.0.2itsdangerous==1.1.0Jinja2==2.10MarkupSafe==1.1.0python-dotenv==0.9.1simplejson==3.16.0Werkzeug==0.14.1

~/python3_flask$ pip3 install -r requirements.txt

3.2 Hello World

Create a first program.

~/python3_flask$ ./hello_world_flask.py * Serving Flask app "hello_world_flask" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 314-551-068

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 1: Flask - hello world program

Page 8: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-8 Python programming

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 9: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-9

It is possible to call the program directly if lines 11 and 12 from Illustration 1 are left out.For example:

~/python3_flask$ cat hello_world_flask_2.py #! /usr/bin/env python3

from flask import Flaskapp = Flask(__name__)

@app.route('/')

def hello_world(): return 'Hello, World!'

Set the following environment variables and then run flask.

~/python3_flask$ export FLASK_APP=hello_world_flask_2.py ~/python3_flask$ export FLASK_DEBUG=1

~/python3_flask$ flask run * Serving Flask app "hello_world_flask_2.py" * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Considering each line of the code. Import the Flask module from the flask package.Flask used to create instances of web application.

from flask import Flask

Create an instance of the Flask class. The __name__ is a special built-in variable thatreturns the name of the module. If the module is being executed as the main programthen __main__ equals __name__ in python, it will equal to “__main__” if the module(python file) being is executed as the main program.

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 2: Flask - hello world

Page 10: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-10 Python programming

app = Flask(__name__)

An @app.route() decorator is applied to functions. Connections for the particular routeexecute the associated function of the associated descriptor. For example the [email protected]("/www") would be accessed by browsing to localhost:5000/www/.

The root of the webserver must be defined. In this case the root is the localhost:5000/.

@app.route("/")

Define a function that will be executed when a browser accesses the localhost:5000/route.

def hello_world(): return "Hello World!"

Run the app instance and enable debug which will output errors as necessary.

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

4. Jinja2

Jinja2 is the python template engine, it has full unicode support, an optional integratedsandboxed execution environment, widely used and BSD licensed.

Illustration 3 is a simple example of a Jinja2 template. It is a HTML file which includesitems in {{ }}. for example a_title is a variable that is inserted by the Flaskrender_template function.

This file is placed in a templates directory that is relative to the route() that the Fleskprogram will call.

~/python3_flask$ mkdir templates

~/python3_flask$ cp jinja_template.html templates

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 11: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-11

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 12: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-12 Python programming

The associated application program is shown in Illustration 4. Therenderer_template() takes the variables given and inserts them as appropriate in thejinja2 template. Notice in the case of the lists how a jinja2 for loop is inserted within thetemplate.

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Illustration 3: Simple Jinja2 template

Page 13: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-13

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 4: Simple jinja2 application

Page 14: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-14 Python programming

The resultant webpage is shown in Illustration 5.

It is worth noting that if run(debug=True) is set then significant debugging informationis made available as shown in Illustration 6 when line 22 is changed to t_list = t_lists,.

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Illustration 5: Flask and Jinja2 webpage rendered

Illustration 6: Debugging Jinja2 and Flask

Page 15: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-15

4.1 Jinja2 Template Inheritance

Jinja2 templates can make use of the concept of inheritance by using the tags {%extends %} and {% block %}.

This is very useful as a common wrapper template to keep common items likenavigation bar, CSS stylesheets, etc..). Inheritance means that these common elementsexist within the base template and child templates inherent them from the base code.

The template in Illustration 7 is an example. Note the {% block content %}{%endblock %} on line 20. The jinja child template will be inserted here.

Illustration 8 shows the jinja child template. Note how it extends the base template withthe first line {% extends "jinja_base_template.html" %}. The block that extends thebase template is between the {% endblock %} and {% block content %} tags.

The final step is to change the jinja2_app.py program to point to the child template. Editline five as follows:

j2_template = 'jinja_child_template.html'

Refresh the browser and the output will look that that shown in Illustration 9.

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 7: Jinja2 base template

Page 16: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-16 Python programming

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Illustration 8: Jinja child template

Page 17: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-17

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 18: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-18 Python programming

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Illustration 9: Jinja and Flask output demonstrating inheritance

Page 19: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-19

5. Web-services RESTful API

Create a requirements.txt file with the requirements inside. This is a simple way tomanage requirements rathar than installing one by one with pip3.

~/python3_flask$ cat << EOM >> requirements.txt Flask-HTTPAuth==3.2.4Flask-RESTful==0.3.6six==0.3.6EOM

~/python3_flask$ pip3 install -r requirements.txt

5.1 Run the server

The Fibonacci RESTful API in Illustration 10 demonstrates an API that requires tokenbased authentication. Run the server.

~/python3_flask$ ./rest.py * Serving Flask app "rest2" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 201-835-620

5.2 Testing the server

Access the server using cURL transfer a URL tool. This tool is useful for transferringdata to or from a server. Browse to port 5000. The input URL will be directed to thedecorator @app.route(‘/’) and the index() function. This results in the message in lines16 to 22 being directed to the browser.

~$ curl http://localhost:5000

Fibonacci series calculatorThis calculates the fibonacci series for a number of elements.You need to put a number at the end, for example.

$ curl -X GET -H "Authorization: Token <secret>" http://localhost:5000/<number>

Browsing to port 5000 with a number will be handled by @app.route('/<int:num>') andthe index2() function. There is an additional decorator here @auth.login_requiredassociated with the auth object created on line 8. If no token or the incorrect token idpresented then the user is presented with an unauthorised access message.

~$ curl -X GET http://localhost:5000/5

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 20: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-20 Python programming

Unauthorized Access

~$ curl -X GET -H "Authorization: Token wrongSecret" http://localhost:5000/5Unauthorized Access

Browsing to port 5000 with a number and a valid token which is confirmed by thedecorator @auth.verify_token and the function verify_token(token) will result in theusername associated with the correct token being stored in the variableg.current_user. The program will then supply the number given to thefibonacci_json() function. This function creates the fibonacci generator object fg whichcan process elements of the Fibonacci series up to 20,000, the value given in theelements variable.

The fibonacci_json() function then creates an attribute value pair for the user:g.current_user and adds it to the element_dict dictionary. It then loops through theFibonacci series elements requested and creates attribute value pairs<position>:<Fibonacci value> and adds them to the element_dict dictionary. Thedictionary is then converted into a string of the JSON format. JSON is a very commonlanguage independent data format used for asynchronous browser–servercommunication. This string is returned to the client.

~$ curl -X GET -H "Authorization: Token secret1" http://localhost:5000/5{"user": "Bob", "0": 0, "1": 1, "2": 1, "3": 2, "4": 3, "5": 5}

~$ curl -X GET -H "Authorization: Token secret2" http://localhost:5000/6{"user": "Alice", "0": 0, "1": 1, "2": 1, "3": 2, "4": 3, "5": 5, "6": 8}

Alternatively to cURL transfer the URL to the server using a URL browser like RESTerin Mozilla can be used as demonstrated in Illustration 11.

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Page 21: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-21

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 10: Fibonacci RESTful API

Page 22: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-22 Python programming

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

Illustration 11: RESTer URL browser in Mozilla

Page 23: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-23

6. Running in production

Install a production server. Waitress is a production-quality pure-Python Web ServerGateway Interface (WSGI) server with very acceptable performance. It has nodependencies except ones which live in the Python standard library.

~/python3_flask$ pip3 install waitress

Next link the application to the Waitress server. It doesn’t use the FLASK_APPenvironment variable like flask run does. Import the application by giving the filenamebut drop the .py. Then the waitress serve() function serves the app instance, in thiscase to any browser that can route to the server and on port 8080.

Run the webserver as follows:

~/python3_flask$ ./waitress_serve.py Serving on http://0.0.0.0:8080

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Illustration 12: waitress server

Page 24: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-24 Python programming

7. Exercise

Write a program called “exercise17.py”. With your partner setup your servers andaccess each others servers as directed.

1. Check that Flask-HTTPAuth, Flask-RESTful and six are installed on the host,if not install them. Hint: pip3 list | grep <module>

2. Add a shebang line and a document string “Exercise 16 in Python3”.

3. Import the Flask, g from flask and HTTPTokenAuth from flask_httpauth anddeclare the port 8080 in global variables.

4. Instantiate the Flask and HTTPTokenAuth classes. In the latter case using theToken scheme.

5. Create two tokens, “triangles” and “calculator”.

6. Create a message that will be returned if a browser is used to access the rootwebpage.

7. Create a function that accepts the positional number and returns the triangularseries number in response.

8. Create a function to verify the token. This function is decorated [email protected]_token.

9. Create a function to handle a browser access to the root of the webpage. i.e. nonumber supplied.

10. Create a function to handle a connection with a valid token and a positionnumber argument.

11. Call the run() method in the app instance of the Flask class for all IP addressesand for port 8080.

12. List the full program.

13. Make the program executable.

14. Run the program on the server side.

15. Confirm connectivity to the server from the client.

16. Browse to the webserver at port 8080.

17. Use cURL or a browser like the RESTer extension in Mozilla Forefox to accessthe calculator RESTful API giving various numbers and receiving the associatedtriangular series value in response. Try both tokens and try a non existent token.

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020

1 3 6 10 15 21 ...

Triangular Series

Page 25: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

Python programming 16-25

Output should look like this (192.168.22.248 is the IP address of the server in thisinstance).

$ curl -X GET -H "Authorization: Token triangles" http://192.168.22.248:8080/5;echo15

$ curl -X GET -H "Authorization: Token calculator" http://192.168.22.248:8080/12;echo78

$ curl -X GET -H "Authorization: Token calculator" http://192.168.22.248:8080/200;echo20100

$ curl -X GET -H "Authorization: Token calculators" http://192.168.22.248:8080/200;echoUnauthorized Access

07 Jan 2020 Module 17 – Web development with Flask and Jinja2 IT Carlow

Page 26: Module 17 Web development with Flesk and Jinja€¦ · IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020. Python programming 16-3 Table of Contents 1. Introduction

17-26 Python programming

This page is intentionally blank

IT Carlow Module 17 – Web development with Flask and Jinja2 07 Jan 2020