Flask routing and Jinja2 templates in 20 lines
Flask is a microframework. The entire app fits on one screen: import `Flask`, instantiate an app object, decorate functions with `@app.route` to bind URL paths, run with `app.run(debug=True)`. The decorator pattern is the central abstraction. A function below `@app.route("/hello")` becomes the handler that runs when a browser requests `/hello`.
URL parameters arrive through angle-bracket syntax in the route and matching keyword arguments in the handler. `@app.route("/user/
Jinja2 is Flask's templating engine. Templates live in a `templates/` directory next to the script. `render_template("page.html", name=username)` reads the file, replaces `{{ name }}` with the value, and returns HTML. Control flow uses `{% if %}` and `{% for %}` blocks. Template inheritance through `{% extends "base.html" %}` plus named `{% block content %}` regions keeps a header and footer in one place across every page. A CS50W problem set typically demands inheritance plus a Bootstrap base, so practicing the extends pattern matters.
# Requires: pip install flask
from flask import Flask, render_template_string, request
app = Flask(__name__)
# Inline template stands in for a templates/index.html file
HOME = """
<h1>Hello, {{ name }}</h1>
<form method="post" action="/echo">
<input name="msg" placeholder="Say something">
<button type="submit">Send</button>
</form>
"""
@app.route("/")
def home():
return render_template_string(HOME, name="student")
@app.route("/user/<username>")
def show_user(username):
return f"<h1>Profile: {username}</h1>"
@app.route("/echo", methods=["POST"])
def echo():
msg = request.form.get("msg", "")
return f"You said: {msg}"
if __name__ == "__main__":
app.run(debug=True, port=5000)