Skip to content

Flask

Flask is a python web framework.

WSGI

Web Server Gateway Interface

Is a protocol of communication used so the request from the webserver can reach the web app, in this case Flask.

Jinja 2

It is a web template engine, that can combine templates with data sources. A data source can be for example:

  • CSV Sheet
  • SQL Database
  • NoSQL Database
  • Machine Learning model

Those below are astral/uv script dependencies, it can be define inside script file. You can run it like uv run my_script.py then they will be automatically installed

1
2
3
4
5
6
# /// script
# requires-python = ">=3.13"
# dependencies = [
#     "flask",
# ]
# ///
1
2
3
from flask import Flask, jsonify, render_template, request

app = Flask(__name__)  # WSGI compliant application instance

We can also serve html templates:

templates/index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >
  <title>Document</title>
</head>

<body>
  <h1>Hello, World!</h1>
</body>

</html>

Is needed to define the route that will serve the template:

1
2
3
@app.route("/")
def home():
    return render_template("index.html")  # root_dir/templates/index.html

GET Route

1
2
3
@app.route("/health", methods=["GET"])
def health():
    return {"status": "ok"}

We can receive inputs from the UI

templates/form.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >
  <title>Document</title>
</head>

<body>
  <h1>My Form</h1>
  <form
    action="/form"
    method="post"
  >
    <label for="name">Name:</label>
    <input
      type="text"
      id="name"
      name="name"
    >
    <button type="submit">Submit</button>
  </form>
</body>

</html>

The inputs come from verbs like POST, PUT and PATCH

1
2
3
4
5
6
@app.route("/form", methods=["GET", "POST"])
def form():
    if request.method == "POST":
        name = request.form["name"]
        return f"Hello {name} !"
    return render_template("form.html")

Dynamic template

Jinja2 Templating engine

  • {{ }}: Expressions
  • {%...%}: Conditions
  • {#...#}: Comments
templates/result.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
  >
  <title>Document</title>
</head>

<body>
  <h1>the mark you got is {{ result }}</h1>
</body>

</html>

Route with params

1
2
3
@app.route("/success/<int:score>")
def success(score):
    return render_template("result.html", result=score)

Running the application

1
2
3
4
if __name__ == "__main__":
    app.run(
        debug=True,  # Enables hot reload if True
    )