Skip to content

Flask

What is Flask

site  

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.

WSGI = Web Server Gateway Interface
A specification for communication between a web server and a Python-based web application (such as Flask).

Install

%  mkdir flask_test
%  cd flask_test
%  python3 -m venv .venv
%  source .venv/bin/activate
(.venv)  %  pip install flask
To escape from venv

(.venv) % deactivate

Code

(.venv)  %  touch app.py
(.venv)  %  nano app.py
app.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask import Flask, render_template

app = Flask(__name__)

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

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

(.venv)  % mkdir templates
(.venv)  % touch templates/index.html
index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
<head>
    <title>Flask Test</title>
</head>
<body>

    <h1>Hello HTML!</h1>

</body>
</html>

Run

(.venv)  %  python3 app.py
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 950-322-917

alt text

Save a list of Python libraries

(.venv)  %  tree
.
├── app.py
└── templates
    └── index.html

(.venv)  %  pip freeze > requirements.txt
(.venv)  %  tree                         
.
├── app.py
├── requirements.txt
└── templates
    └── index.html

(.venv)  %  cat requirements.txt 
requirements.txt
1
2
3
4
5
6
7
blinker==1.9.0
click==8.3.3
Flask==3.1.3
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.3
Werkzeug==3.1.8
To work in the same evnironmant

pip install -r requirements.txt

HTML -> Python -> HTML

templates/index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
    <title>Button Test</title>
</head>
<body>

    <h1>Counter: {{ counter }}</h1>

    <a href="/up">
        <button>+1</button>
    </a>

</body>
</html>
app.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from flask import Flask, render_template

app = Flask(__name__)

counter = 0

@app.route("/")
def home():
    global counter
    return render_template("index.html", counter=counter)

@app.route("/up")
def up():
    global counter
    counter += 1

    return render_template("index.html", counter=counter)

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

alt text