Flask & Deployment
Topic 2 · Web apps with Flask · ⏱ about 2.5 h

Your First Flask App

Set up a project with a virtual environment, write routes that return text, HTML and JSON, read URL variables, query strings and request data, run the development server, and understand what debug mode does.

Show:
In this topic
Beginner

Set up a project

Make a folder for the project, create a virtual environment (a private set of packages for this project; see developer tools), and install Flask:

mkdir clinic-app && cd clinic-app python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install flask pip freeze > requirements.txt # record exact versions for later
Beginner

Hello, Flask

Save this as app.py, run flask --app app run --debug in the terminal, and open http://127.0.0.1:5000 in your browser.

Python (app.py)
from flask import Flask, request

app = Flask(__name__)            # the application object

@app.route("/")                  # when someone requests "/", run this function
def home():
    return "<h1>Hello, clinic!</h1><p>Try <a href='/patients/7'>/patients/7</a></p>"

@app.route("/patients/<int:patient_id>")     # a URL variable, converted to int
def patient(patient_id):
    return {"id": patient_id, "name": f"Patient {patient_id}"}   # a dict becomes JSON

@app.route("/search")
def search():
    q = request.args.get("q", "")            # the query string: /search?q=sita
    return {"query": q, "results": []}
This code runs a web server with Flask, which cannot run inside this page. To run it on your computer: install Python, run pip install flask, save the code as app.py, then run flask --app app run --debug and open http://127.0.0.1:5000. Press Copy to take it with you.
Beginner

Routes and requests

  • @app.route("/path") connects a URL to a view function. Whatever the function returns becomes the response: a string (HTML), a dict or list (sent as JSON), or a tuple like (body, 201) to set the status code.
  • URL variables: /patients/<int:patient_id> matches /patients/7 and passes patient_id=7. Converters include int, float, path and the default string.
  • By default a route only accepts GET. Allow others with @app.route("/patients", methods=["GET", "POST"]), or the shortcuts @app.get and @app.post.
  • The request object holds the incoming request: request.args (query string), request.form (submitted form fields), request.get_json() (a JSON body), request.headers and request.method.
Try it

Try it: which route matches?

Type a path (or pick one) and see which route Flask would run, and with which variables. Flask checks the method too.

Interactive: this part runs in your browser.

Beginner

The development server and debug mode

flask run starts a development server: fine on your laptop, but not for real users; it is slow and not hardened. In production you use a proper server such as gunicorn (see deployment).

--debug reloads the app when you save a file and shows an interactive error page in the browser. That page can run Python code on your machine, so never turn debug mode on in production.

Check yourself

Quiz

1. What does @app.route("/about") do?

2. A Flask view returns {"ok": True}. What does the client receive?

3. Why must debug mode be off in production?

4. How do you read ?page=2 in a view?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready