CS50x - Lecture 9 - Flask
Watch on YouTube →
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
0:43
Introduction to Web Programming and Flask
- 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.
3:20
Understanding URLs, Routes, and HTTP Servers
- 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.
9:53
Creating a Basic Flask Application ('Hello World')
- 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!').
20:31
Rendering HTML Templates with Flask
- 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.
28:30
Handling User Input with Request Arguments
- 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.
35:13
Implementing Conditional Logic in Templates
- 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).
47:10
Combining GET and POST Routes with Conditional Logic
- 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`).
1:00:05
Refactoring HTML with Layout Templates
- 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.
1:10:53
Distinguishing GET vs. POST Requests for Security
- 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`.
1:20:51
Combining Routes and Handling Multiple Forms
- 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.
1:26:51
Adding Dynamic Error Messages to Templates
- 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.
1:35:07
Implementing a Frosh IMs Registration Form
- 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.
1:55:31
Validating User Input on the Server-Side
- 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.
1:58:40
Centralizing Data with Global Variables and Loops
- 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`.
2:05:01
Implementing Radio Buttons and Checkboxes in Forms
- 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.
2:15:34
Storing Registration Data in an SQLite Database
- 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.
2:18:51
Querying and Displaying Database Records
- 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>`).
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, CS50.