Introduction

What is Flask?

Flask is a micro-framework for the web, written in Python.

Micro because the basis for its functionality is extremely limited, in spite of its numerous extensions.

Used for creating websites and APIs.

Flask is based on the projects Werkzeug and Jinja 2.

Why use Flask?

  • Easy to learn.

  • Pythonic (adopts the principles and style of programming from Python).

  • Small/light but scalable for big applications.

  • Decorator defined routes

Development

Environment creation

$ mkdir project
$ cd project
$ mkdir static
$ mkdir templates
$ touch app.py
$ chmod +x app.py
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install Flask

Routing/Redirect

from flask import redirect, url_for

@app.route("/user/<name>")
def say_hi(name):
    return f"Hi {name}"
    
@app.route("/index.html")
def index2():
    return redirect(url_for('index')) # index is the name of a function

Static

Files in the static directory are served directly (without the need for any code):

  • Useful to place images, JavaScript, CSS, etc.

Jinja2 templates

hello.html

<!doctype html>HP
<title>Hello</title>
{% if name %}
    <h1>Hello {{ name  }}</h1>
{% else %}
    <h1>Hello World</h1>
{% endif %}
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/user")
@app.route("/user/<name>")
def say_hi(name=None):
    return render_template("hello.html", name=name)

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

users.html

<!doctype html> 
<title>Hello</title> 
{% for user in users %}
    <h1>Hello {{ user }}</h1>
{% endfor %}
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/users")
def list_users():
    users = [“Diogo”, “Gomes”]
    return render_template(”users.html", users=users)
    
if __name__ == "__main__":
    app.run()

HTTP methods

@app.route("/login", methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return f"Welcome { request.form['username'] }"
    else:
        return "curl -X POST -F 'username=dgomes' http://localhost:5000/login"

Receive a file through a POST request

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    file.save(file.filename)
    return f"Thank you"

Last updated