CS50x - Lecture 9 - Flask
Overview
CS50's Week 9 introduces web programming using Python and Flask, synthesizing previous concepts to build dynamic web applications. David J. Malan demonstrates creating routes, rendering HTML templates, handling user input via GET and POST requests, managing sessions with cookies, and interacting with SQLite databases for persistent storage, culminating in a functional Frosh IMs registration system.
Key takeaways
- Flask simplifies web development by handling HTTP requests, routing, templating, sessions, and database integration.
- User input must always be validated server-side (e.g., checking `request.form` and database constraints) to prevent security vulnerabilities like SQL injection.
- Sessions, implemented via cookies, allow web applications to maintain user state (like login status or shopping cart contents) across stateless HTTP requests.
- Separating concerns using the MVC (Model-View-Controller) pattern improves code organization and maintainability.
- APIs, often returning JSON, enable different applications (web, mobile, other services) to interact with your data and functionality programmatically.
- Static files (images, CSS, JS) should be placed in a `static` folder, while dynamic templates reside in a `templates` folder.
Chapters
- Week 9 synthesizes past concepts for web application development.
- Web applications involve server-side logic (Python) and client-side presentation (HTML, JavaScript).
- Flask is a Python microframework simplifying web server creation.
- URLs map to server paths or 'routes'.
- HTTP server (e.g., `http.server`) serves static files.
- Flask's `flask run` starts a development server for dynamic applications.
- Minimal Flask app requires `app.py` and `requirements.txt`.
- Import `Flask` from the `flask` library.
- Use `@app.route('/')` decorator to associate a function with a URL path.
- The `index` function returns the response (e.g., 'Hello, world!').
- Return HTML strings directly or use `render_template`.
- Flask looks for templates in a `templates` directory by convention.
- Create `index.html` within the `templates` folder.
- Access URL parameters (GET requests) via `request.args`.
- Use `request.args.get('param_name', 'default_value')` for safe access.
- Jinja templating (curly braces `{{ variable }}`) interpolates Python variables into HTML.
- Jinja supports Python-like control flow (e.g., `{% if ... %}`, `{% else %}`, `{% endif %}`).
- Use `request.form.get('param_name')` for POST request data.
- The `request.method` attribute checks the HTTP verb (GET or POST).
- Modify `@app.route` to accept multiple HTTP methods (e.g., `methods=['GET', 'POST']`).
- Use `if request.method == 'POST':` to differentiate form submissions.
- Update form `action` attribute to submit to the correct route (e.g., `/` or `/greet`).
- Create a `layout.html` file for common boilerplate HTML (doctype, head, body structure).
- Use Jinja's `{% extends 'layout.html' %}` to inherit from the layout.
- Define `{% block body %}` sections in child templates to insert unique content.
- GET requests append parameters to the URL, visible in history and logs.
- POST requests send data in the request body, offering better privacy.
- Use `methods=['POST']` on routes handling sensitive data.
- Access POST data via `request.form` instead of `request.args`.
- Consolidate related routes (e.g., form display and submission) into a single function.
- Use `if request.method == 'POST':` to conditionally execute logic.
- Update form `action` attribute to submit to the consolidated route.
- Create a generic `error.html` template.
- Pass specific error messages from Python to the template using `render_template(..., message='...')`.
- Display the message using Jinja's `{{ message }}` interpolation.
- Use HTML `<form>`, `<input type='text'>`, `<select>`, and `<button type='submit'>`.
- Set form `action` to `/register` and `method` to `POST`.
- Use `request.form.getlist('sports')` to handle multiple checkbox selections.
- Never trust client-side validation alone; always validate on the server.
- Check if required fields are present (`if not name:`).
- Validate against allowed values (e.g., `if sport not in SPORTS:`).
- Return specific error messages using a dedicated error template.
- Use global constants (e.g., `SPORTS = [...]`) for maintainable lists.
- Dynamically generate HTML form options using Jinja loops (`{% for sport in SPORTS %}`).
- Pass global data (like `SPORTS`) to templates via `render_template`.
- Radio buttons (`type='radio'`) with the same `name` attribute create mutually exclusive selections.
- Checkboxes (`type='checkbox'`) allow multiple selections.
- Use `request.form.getlist()` to retrieve values from multiple checkboxes.
- Use CS50's `SQL` library for database interaction.
- Create a `shows.db` (or `froshims.db`) SQLite database file.
- Define tables (e.g., `registrants` with `id`, `name`, `sport`) using SQL `CREATE TABLE`.
- Execute SQL `INSERT` statements using parameterized queries (`?` placeholders) to prevent SQL injection.
- Execute `SELECT * FROM table` to retrieve all records.
- The `db.execute` function returns a list of dictionaries.
- Iterate through the list of dictionaries in Jinja (`{% for row in variable %}`) to display data in HTML tables (`<table>`, `<tr>`, `<th>`, `<td>`).
Transcript excerpt
0:43 All right, this is CS50. This is already week 9, and I dare say this week is the most representative of what you'll be doing after the class if you so choose to program in the future and tackle some project that's new to you. In fact, the closest to this week was perhaps week 6, wherein we didn't really introduce all that many new concepts but really translated them from C into Python. And so this week, in particular, the goal is to really synthesize the past 10 weeks of class, drawing upon a lot of the building blocks that are. Hopefully now, metaphorically in your toolbox and gives you an opportunity now to apply those ideas to new problems, in particular web programming. So every day you and I are using the web in some form, every day you and I are using mobile apps in some form, and we said last week that the languages underlying a lot of those applications are HTML and JavaScript for the layout and aesthetics,
1:31 and then also in part JavaScript for a lot of the client side interactivity that you might experience nowadays. Well today we come full circle and bring back a server. Side component whereby we'll again write some Python, we'll again write some SQL code and use it to make our full fledged own web applications and in turn if you so choose mobile applications as for your final project as well. So up until now when we did anything with the web, you ran this command last week, HTTP server, which literally did just that. It spawned a so-called HTTP server that is a web server whose purpose in life is just to serve up content from like your current folder, any files they're in, any folders therein.
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, CS50.