Introduction to Computer Science: Harvard CS50 · Course book
Chapter 8: Building Dynamic Web Applications
Chapter 6 described web pages stored as fixed HTML files that a server sends unchanged to everyone. Much of the web works differently: a search engine builds a new results page for each query, and a shop shows each visitor their own basket. Such pages are dynamic, produced by a program on the server when they are requested. This chapter shows how to write those programs in Python with Flask, a small and widely used web framework, and introduces the core ideas behind every web application: routes, templates, forms, stored data and a clear division of responsibilities.
Routes: matching addresses to code
A web application is a program that waits for HTTP requests and answers each one. Flask does the listening and the parsing of requests; you write the functions that decide what to send back. The smallest application looks like this:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "hello, world"
The line beginning with @ is a decorator. It tells Flask that whenever a request arrives for the path /, it should call the function index and send its return value as the response. Each such pairing of a path with a function is a route. An application usually has many: /, /about, /search, /register, each handled by its own function.
Started with the command flask run, the program becomes a server, usually reachable on your own computer at port 5000. Visiting it in a browser sends a GET request for /, Flask calls index, and the browser shows "hello, world".
Routes can read information from the request. If someone visits /greet?name=Ada, the function can read the parameter with request.args.get("name"), receiving the text "Ada". A second argument supplies a default, so request.args.get("name", "world") returns "world" when no name was given. This is how a single route serves different content to different visitors.
Templates: HTML with gaps to fill
Returning plain text is not enough for real pages, but writing whole HTML pages inside Python strings quickly becomes unreadable. Instead, the HTML lives in separate files called templates, stored in a folder named templates, with placeholders where values should go. Flask uses a templating language called Jinja.
<!-- templates/greet.html -->
<!DOCTYPE html>
<html>
<body>
<p>hello, {{ name }}</p>
</body>
</html>
The route then renders the template, passing in the value:
@app.route("/greet")
def greet():
name = request.args.get("name", "world")
return render_template("greet.html", name=name)
Double curly braces insert a value. Jinja also offers simple logic between {% and %}: a {% for %} block can repeat a list item for every element of a list, and an {% if %} block can show a message only when something is true. Jinja automatically escapes inserted values, turning characters such as < into harmless codes, so text typed by a visitor is shown as text instead of being treated as HTML.
Most pages on a site share the same outer frame: the same head, navigation and footer. Rather than repeating it, a layout template holds the frame with a named empty block, and each page template states that it extends the layout and supplies only the block's contents. Changing the navigation then means editing one file.
Templates can loop over data passed to them. Suppose a route passes a list of three sports, ["Football", "Tennis", "Swimming"], to a template containing a select menu. A {% for sport in sports %} block around a single <option> line produces three options, one per sport, and adding a fourth sport to the Python list adds a fourth option to the page with no change to the HTML. Keeping such lists in one place in the Python code, and passing them to every template that needs them, means the form and the code that checks the form can never disagree about which choices exist.
Forms, GET and POST
Forms let visitors send information to the application. A form's action attribute names the route that will receive it, and its method attribute says how the data travels. The two methods suit different jobs.
| Property | GET | POST |
|---|---|---|
| Where the data goes | In the address, after a question mark | In the body of the request |
| Visible in the address bar and history | Yes | No |
| Can be bookmarked or shared | Yes | No |
| Read in Flask with | request.args | request.form |
| Typical use | Searches and filters | Registrations, log-ins, anything that changes data |
A route can accept both methods and behave differently for each: on GET, show the empty form; on POST, process what was submitted. The decorator lists the methods allowed, as in @app.route("/register", methods=["GET", "POST"]), and inside the function request.method says which one arrived.
After a successful POST, a well-behaved application usually sends a redirect, a response with status 302 telling the browser to load another page, such as a list of everyone registered. This avoids a common annoyance: if the success page were returned directly, refreshing it would ask the browser to submit the form a second time. Flask's redirect function produces such a response in one line.
Checking the input on the server is essential. HTML can mark a field as required, and the browser will then refuse to submit an empty form, but anyone can bypass a browser's checks. The server must therefore confirm for itself that each field is present and sensible, for instance that a chosen option is one of those actually offered, and reply with a helpful error page if not.
Keeping data: memory, files and sessions
An application that accepts registrations needs somewhere to keep them. The simplest place is a Python variable, such as a list or dictionary defined at the top of the program. That works for a demonstration but has an obvious flaw: when the server restarts, the data vanishes, and if the application runs on several servers, each has its own separate copy.
A step up is to write each registration to a file, for example a CSV file, comma-separated values, which spreadsheets can open. Python's csv module writes one row per registration. Files survive restarts, but they become awkward when many visitors write at once or when you need to search and update entries. That is the job of a database, the subject of Chapter 9.
A different kind of memory is needed to recognise a returning visitor. HTTP itself has no memory: each request is independent. Applications get round this with cookies, small pieces of data that the server asks the browser to store and send back with every later request to the same site. Flask builds a session on top of cookies: a dictionary, available as session, in which the application can store values for one visitor, such as their name after they log in or the items in their basket. The data is kept so that the visitor cannot alter it unnoticed, and it lasts until the session ends.
Organising an application: MVC
As applications grow, it helps to separate three concerns, a pattern called model, view, controller, or MVC.
In a Flask application the controller is the Python file of routes, which decides what each request should do. The model is the data and the code that reads and writes it. The view is the templates, which only present what they are given. Keeping the three apart means the look of a page can change without touching the data logic, and the data can move from a file to a database without rewriting any templates.
A typical small Flask project therefore has a recognisable shape: an app.py file holding the routes, a templates folder holding the HTML, a static folder holding style sheets, images and scripts that are sent unchanged, and a file or database holding the data. Anyone familiar with Flask can open such a project and know at once where to look for each part.
Applications can also offer data instead of pages. A route that returns information in a format called JSON, rather than HTML, lets JavaScript in the browser fetch fresh results without reloading the whole page, for example showing search suggestions while someone types. Such routes are a simple form of an API, an interface designed for programs rather than people.
Check your understanding
- What is a route, and what does the decorator @app.route("/about") do?
- For the address /greet?name=Lin, what does request.args.get("name", "world") return? And for /greet? (Answer: "Lin", and "world".)
- Why do templates escape inserted values automatically?
- Which method suits a search form, and which a registration form? Why?
- Why must input be checked on the server even if the HTML form marks fields as required?
- What is lost when registrations are kept only in a Python list, and how does a file help?
- In MVC, which part would you change to redesign a page's appearance?
This course book is available to read online only at tech-academy.chrysolites.org.