Flask flashcards
A small Python web framework you grow as you go.
Beginner friendly, starts from zero
0
Flask at a glance
Flask is a small Python toolkit that runs your functions when someone visits a web address.
Flask is a waiter: it takes each order, hands it to the right cook (your function) and brings the dish back.
Words you will meet
- Route
- A link between a web address and one of your functions
- View
- The Python function that answers a route
- Request
- What the browser or app sends to your server
- Response
- What your server sends back, with a status code
- Template
- An HTML file with gaps that Flask fills with data
- JSON
- A plain-text way to write data that apps can read
- Virtual environment
- A private folder of packages for one project
- Production
- The live server that real users visit
The steps
- 1. Start from zero (12 cards): What Flask is, how a web request works, and the words you need before your first route.
- 2. Core basics (16 cards): Your first app, routes, requests, JSON, templates and error output.
- 3. Next steps (16 cards): Blueprints, the app factory, config, sessions, forms, tests and extensions.
- 4. Go deeper (16 cards): Contexts, async views, deployment, proxies, security, streaming and resilience.
All 12 cards in Start from zero
- What is Flask, in one plain sentence?
- Flask is a small Python toolkit for building websites and web services: you write a Python function, and Flask runs it whenever someone visits a certain web address.
- What problem does Flask solve? What was it like without it?
- Without it you would read raw web traffic yourself, work out which page was asked for and format every reply by hand. Flask does that plumbing so you only write what each page should do.
- Where do you already meet something like Flask every day?
- When you tap Track order in an app, a program on another computer looks up your order and sends it back. Small services like that are often written with Flask.
- What everyday thing is Flask like?
- A waiter in a restaurant. He takes each order from a table, passes it to the right cook, and brings the dish back. Flask takes each request, calls the right function and returns its answer.
- What are a server, a client and production?
- A server is a program that waits for requests and answers them. A client is whatever asks: a browser or a phone app. While you learn, your laptop is the server; the live one for real users is called production.
- What are a URL, a route and a view?
- A URL is a web address, like
/orders/42. A route links a URL to one of your Python functions, and that function is called a view. - What are a request, a response and a status code?
- The request is what the client sends: the address, a method like GET (read) or POST (send data), and any data. The response is your reply plus a status code: 200 means OK, 404 not found, 500 server error.
- What are JSON and an API?
- JSON is a plain-text way to write data, like
{"status": "ok"}. An API is a set of web addresses that apps call to get or send data, usually as JSON, instead of web pages. - What are HTML and a template?
- HTML is the text that describes a web page. A template is an HTML file with gaps, like
{{ name }}, that Flask fills with real data before sending it. Flask's template language is called Jinja. - What are the terminal, a package and a virtual environment?
- The terminal is a window where you type commands. A package is ready-made code you install with
pip; Flask is one. A virtual environment is a private folder of packages for one project. - What do you need, and what is your first tiny win?
- Python and
pip install flask. Save this asapp.py, runflask --app app runand openlocalhost:5000(your own computer). The route/runs the viewhome, which returns the text. - What will you be able to do after this topic?
- Build a small website or JSON API in Python, read form and URL data safely, show pages from templates, and run it properly in production with logging and error pages.
Flask cheatsheet
Routing
@app.get("/orders/<int:order_id>")Typed URL variable@app.route("/x", methods=["GET", "POST"])One view, two verbs<path:subpath> / <uuid:token>Slash-capturing / UUID convertersurl_for("orders.detail", order_id=7)Build URL by endpointBlueprint("orders", __name__, url_prefix="/orders")Feature moduleapp.add_url_rule(rule, view_func=V.as_view("v"))Register a class view
Request
request.args.get("page", 1, type=int)Typed query valuerequest.args.getlist("tag")Repeated query keysrequest.form["email"]Form field (400 if missing)request.get_json(silent=True)JSON body or Nonerequest.files["photo"]Uploaded filerequest.headers.get("X-Request-Id")Header valuerequest.remote_addrClient IP (useProxyFix)
Response
return {"ok": True}, 201JSON with statusreturn body, 200, {"Cache-Control": "no-store"}Add headersredirect(url_for("home"), code=303)Redirect after POSTabort(404)Stop with an errorsend_file(path, as_attachment=True)Download a fileResponse(gen(), mimetype="text/csv")Stream outputmake_response(...).set_cookie(...)Edit response before returning
CLI
flask --app orders run --debugDev server with reloadflask --app "orders:create_app()" runRun a factoryflask routesList every URL ruleflask shellPython shell with app contextflask db migrate -m "add sku" && flask db upgradeFlask-Migrate schema changegunicorn "orders:create_app()" -w 4 -b 127.0.0.1:8000Production server
Config and state
app.config.from_prefixed_env()ReadFLASK_*env varsSECRET_KEY / SECRET_KEY_FALLBACKSSign sessions / rotate keys (3.1+)MAX_CONTENT_LENGTHMax request body, 413 aboveSESSION_COOKIE_SECURE / _SAMESITECookie hardeningg.userPer-request storagecurrent_app.config["KEY"]Config from inside any codewith app.app_context():Context for scripts and jobs