CS50 Fall 2025 - Lecture 9 - Flask (live, unedited)
Overview
CS50's Lecture 9 introduces web programming with Python's Flask microframework, synthesizing past concepts to build dynamic web applications. The lecture covers routing, HTML templating with Jinja, handling user input via GET and POST requests, session management with cookies, database integration using SQLite, and building APIs that return JSON data, culminating in a Frosh IMs registration system and a simple bookstore.
Key takeaways
- Flask simplifies web development by handling routing, request parsing, and templating.
- Sessions, implemented via cookies, enable stateful interactions like user logins and shopping carts.
- Databases (SQLite) provide persistent storage for application data, crucial for real-world applications.
- Server-side validation is essential to secure applications against malicious input.
- APIs returning JSON allow data to be consumed by various clients, including JavaScript frontends.
- The MVC pattern (Model-View-Controller) provides a structured approach to organizing web application code.
Chapters
- Week 9 synthesizes past concepts for web programming, focusing on building full-fledged web applications.
- Web applications combine client-side (HTML, JavaScript) and server-side (Python, SQL) components.
- Flask is a Python microframework for simplifying web server development.
- URLs map to routes, which are handled by server-side code.
- Routes can accept parameters via query strings (e.g., ?key=value).
- Flask's `app.route` decorator associates URL paths with Python functions.
- A minimal Flask app requires `from flask import Flask` and `app = Flask(__name__)`.
- The `@app.route('/')` decorator maps the root URL to a function.
- Functions decorated with `@app.route` return the content displayed in the browser.
- Hardcoding HTML in Python is cumbersome; use `render_template` for external HTML files.
- HTML files for Flask templates reside in a `templates` directory.
- `render_template('index.html')` renders the specified HTML file.
- Flask's `request` object provides access to incoming request data.
- `request.args.get('parameter_name')` retrieves GET parameters from the URL.
- Templates can use Jinja syntax `{{ variable_name }}` to display dynamic data.
- Jinja templating supports Python-like control flow, including `if`/`else` statements.
- `{% if condition %}` ... `{% else %}` ... `{% endif %}` structures dynamic content.
- Whitespace in HTML is generally ignored by browsers, simplifying template formatting.
- Web applications can have multiple routes (e.g., `/`, `/greet`).
- HTML forms use `method='post'` to send data securely without exposing it in the URL.
- Flask routes can specify supported HTTP methods using `methods=['GET', 'POST']`.
- POST data is accessed via `request.form.get('field_name')`.
- This differs from GET parameters accessed via `request.args`.
- Using `request.form.get('field_name', 'default_value')` provides a fallback.
- A single route can handle both GET (displaying form) and POST (processing form) requests.
- Check `request.method == 'POST'` to differentiate request types.
- The form's `action` attribute should point to the route handling the submission (e.g., `/`).
- Duplicate HTML boilerplate (head, body tags) can be factored into a `layout.html` template.
- Jinja's `{% extends 'layout.html' %}` directive inherits from a base template.
- `{% block block_name %}` ... `{% endblock %}` defines areas for content insertion.
- HTML checkboxes allow users to select multiple options.
- Flask's `request.form.getlist('parameter_name')` retrieves all selected checkbox values.
- Server-side validation ensures submitted data is valid (e.g., sport is in a predefined list).
- Radio buttons (`type='radio'`) allow selecting one option from a group.
- Using the same `name` attribute for radio inputs enforces mutual exclusivity.
- Server-side validation is crucial to prevent malicious or incorrect data submission.
- Custom error templates (`error.html`) provide specific feedback to users.
- Pass error messages as variables to templates using `render_template('error.html', message='...')`.
- Static files (images, CSS, JS) are served from a `static` directory.
- Global variables in Flask are lost on server restart; use a database for persistence.
- CS50's `SQL` library simplifies SQLite integration.
- `db.execute('INSERT ...')` adds data, `db.execute('SELECT ...')` retrieves data.
- SQL `INSERT` statements add new records.
- SQL `SELECT * FROM table` retrieves all records.
- SQL `DELETE FROM table WHERE id = ?` removes specific records using primary keys.
- HTTP is stateless; sessions provide state persistence using cookies.
- Flask's `session` object (a dictionary) stores user-specific data.
- Cookies act as 'hand stamps' (key-value pairs) sent between browser and server.
- Flask-Session library simplifies cookie-based session management.
- Login route handles POST requests, storing username in `session['name']`.
- Logout route clears the session using `session.clear()`.
- Sessions enable persistent shopping carts across user requests.
- `session['cart'] = []` initializes an empty cart.
- `session['cart'].append(book_id)` adds items; `session.get('cart', [])` retrieves it.
- Jinja loops (`{% for item in list %}`) iterate over data (e.g., books, registrants).
- HTML tables (`<table>`, `<thead>`, `<tbody>`, `<tr>`, `<th>`, `<td>`) structure data.
- Server-side code dynamically generates table rows based on database content.
- Flask's `redirect(url)` function sends the browser to a different URL.
- Used after form submission (POST) to redirect to a GET route (e.g., showing results).
- Prevents accidental resubmission of data by avoiding direct POST to result pages.
- Storing redundant data (e.g., multiple registrations for the same person) is inefficient.
- Database normalization involves creating separate tables for related entities (e.g., students, sports).
- Using primary keys (IDs) ensures unique identification and avoids data duplication.
- Hidden input fields (`<input type='hidden'>`) pass data to the server without user interaction.
- Used to send unique identifiers (like IDs) for actions such as deletion.
- Forms submitting via POST with hidden IDs allow targeted data manipulation.
- GET requests append data to URLs, making it visible and bookmarkable.
- POST requests send data in the request body, enhancing privacy and security.
- Destructive actions (delete, update) should always use POST requests.
- Consolidating related logic into fewer routes simplifies application structure.
- Using `request.form.getlist()` handles multiple selections from checkboxes.
- Server-side validation checks data against predefined lists or rules.
- Global variables (e.g., `SPORTS = [...]`) centralize configuration data.
- Jinja loops (`{% for item in list %}`) dynamically generate HTML elements (e.g., dropdown options, checkboxes).
- This reduces code duplication and simplifies updates.
- APIs (Application Programming Interfaces) provide data services over HTTP.
- Flask's `jsonify()` function converts Python data structures (lists, dicts) to JSON.
- JSON (JavaScript Object Notation) is a lightweight data-interchange format.
- Autocomplete search enhances user experience by suggesting results as the user types.
- Requires JavaScript on the client-side to make asynchronous requests (AJAX) to the server.
- Server-side API routes return JSON data, which JavaScript then uses to populate suggestions.
- MVC is a common architectural pattern for organizing applications.
- Model: Data persistence (database).
- View: User interface (HTML templates).
- Controller: Application logic (Python/Flask code).
- HTTP is stateless; cookies and sessions provide statefulness.
- Cookies are key-value pairs stored by the browser, sent with requests.
- Sessions store user-specific data on the server, linked via cookies.
- Flask-Session simplifies session management.
- Login route stores username in `session['name']` upon successful POST.
- Logout route clears the session via `session.clear()`.
- Demonstrates using sessions to maintain a shopping cart.
- Books are stored in a SQLite database (`store.db`).
- Add-to-cart functionality appends book IDs to `session['cart']`.
- SQL `LIKE` operator enables pattern matching in string searches.
- Wildcards (`%`) allow matching zero or more characters.
- Case-insensitive searches can be implemented using functions like `LOWER()` or database-specific features.
- Server routes can return raw HTML fragments (e.g., `<li>` tags) instead of full pages.
- This allows JavaScript on the client-side to dynamically update the UI (e.g., autocomplete).
- Requires careful handling of context and potential security implications.
- APIs allow programmatic access to data and services.
- Flask's `jsonify()` function converts Python data to JSON format.
- JSON is widely used for data exchange between web services and clients.
- Review of core concepts: routing, templating, databases, sessions, APIs.
- Emphasis on the MVC paradigm for structuring applications.
- Encouragement to apply learned concepts to final projects.
Transcript excerpt
18:07 All right, this is CS 50. 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. 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,
18:55 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.