+ FLASK NOTES

Some notes while learning Flask

I mostly do animation and pipeline scripting but I try to keep up somewhat with web developement. I do this both because it is fun but I also think it is a really useful skill to have. One thing I recently did was to create a web based shader library. I did this using PHP, but since Python is used everywhere else in the pipline I am looking into recreating the library with Python and replace the PHP version. I have had a quick look at both Django and Flask, and have decided (at least for now) to use Flask. I like the micro framework aspect.

When I learn something I always find it useful to write it down, partly because it sticks better when I process it multiple times but also as notes to future self (or someone else for that matter) I am really enjoying Corey Schafers tutorials, so if you want to have a look at Flask I really recommend his tutorials. This post will be based on his tutorials, various documentation and other pieces of info that I stumble across.


Installation

create a project dir an cd into it.

create an environment

  • osx
    • python3 -m venv venv
      

Activate the environment

  • osx
    • . venv/bin/activate
      

install flask

pip install Flask

Extra packages

  • pip install flask-wtf
    forms, validation etc
  • pip install flask-sqlalchemy
    database (dev)
  • pip install flask-bcrypt
    security
  • pip install flask-login
    login manager, user utils

Flask app

We start by importing and creating an instance of the Flask class. We pass in “__name__” which is a special Python variable which is the name of current module. We do this to inform Flask where to look for files etc.

from flask import Flask
app = Flask(__name__)

Run the app (debug)

There are two ways to run our app, we can either set some environment variablers and use flask run like so: (Note that on Windows we use set instead of export)

  • OSX
    • export FLASK_APP=flaskblog.py
      

If we want to run this in debug mode we can set following environment variable:

  • OSX
    • export FLASK_DEBUG=1
      

Then we run the app:

flask run

Or we can run it using Python. We simple add the following lines to the en off the main app file:

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

And then we enter following lines in the terminal:

python flaskblog.py

Note that we right now do not have any content, we will add content to the site using routes.


Routes

Routes is how we send the user to different pages. In the hello world example the string “Hello World!” is displayed in the browser. We can write HTML here and return but it is much better to do this with templates. The route decorator handle the route requested by the user. Note that multiple route decorators can be used to decorate the route function, i.e. multiple routes can lead to the “same page”. The forward slash in this expamle means to root or home page.

@app.route("/")
@app.route("/home")
def home():
    return "<h1>Hello World!</h1>"

To make an route accept a GET or POST method we need to specify that by adding the methods to the route decorator:

@app.route("/login", methods=['GET', 'POST'])
def login():
	...

Templates

We could write HTML in our route functions and return that but this is obviously not the best way to do it. A much better way is to use templates.

Lets create a directory in our project dir and call it “templates”. In this dir lets create a template for our home route, lets call it home.html

To render this template we will use the render_template function from the falsk module.

from flask import render_template
#...

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

Arguments

The template engine that Flask uses is called jinja2 and it allows us to write code in our template. To use variables in our templates we can simply pass theese to the render_template function:

Lets declare some dummy data to pass to our render_tempalte function

materials = [
	{
		'name':'MAT_1',
		'material_type':'metal',
		'surface_property':'glossy'
	},
	{
		'name':'MAT_2',
		'material_type':'plastic',
		'surface_property':'rough'
	},
]

To render the data passed to the template we first open up a code block in this case a for loop. We then print out the data of the material using dot notation. And finally we close the for loop code block.

{% %}
To open and close a code block
{{ }}
To retrieve a variable

For loop

{% for mat in materials %}
	<h1>{{ mat.name }}</h1>
	<h1>{{ mat.material_type }}</h1>
	<h1>{{ mat.surface_property }}</h1>
{% endfor %}

Conditional

Lets use a conditional to retrieve a variable if it exists. Lets say that we passed in a variable to the home template called title. But we would like to write the template in such a way that it can handle the case that this variable was not provided. To do this we can use a if else code block.

{% if title %}
	<title>{{ title }}</title>
{% else %}
	<title>title</title>
{% endif %}

Template inheritance

As the site grows it is really useful to create a layout template that other templates can inherit from. For instance you might want to include the same css files in the header or load javascripts. To avoid doing this per template we can create one master layout that we inherit from.


Package structure

User auth