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.
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:
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.
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": []}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/7and passespatient_id=7. Converters includeint,float,pathand the defaultstring. - By default a route only accepts GET. Allow others with
@app.route("/patients", methods=["GET", "POST"]), or the shortcuts@app.getand@app.post. - The
requestobject holds the incoming request:request.args(query string),request.form(submitted form fields),request.get_json()(a JSON body),request.headersandrequest.method.
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.
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.
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?
📚 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.
- Flask documentation ↗ the official docs, including the Quickstart
- The Flask Mega-Tutorial (Miguel Grinberg) ↗ a long, free, much-loved tutorial