CS50x en Español - Clase 9 - Flask
Overview
David J. Malan’s CS50 Week 9 lesson builds web applications with Flask, connecting Python routes and Jinja templates to HTML forms, HTTP methods, and SQLite. Through a Frosh IMs registration app and examples for login, shopping carts, search, and APIs, the lesson shows how to validate user input, persist data, manage sessions, and return JSON.
Key takeaways
- Flask routes let Python functions control application behavior, while render_template and Jinja separate reusable HTML presentation from server-side logic.
- GET places parameters in the URL and suits searches or shareable links; POST keeps fields out of the URL, but browser developer tools can still inspect them.
- Client-side menus and checkboxes cannot enforce valid input: the server must validate every submitted value against an authoritative list.
- SQLite provides persistence that in-memory Python dictionaries cannot, and parameterized queries support safe inserts, lookups, and deletions.
- Flask sessions associate per-user state with cookies, enabling features such as login status and shopping carts without placing passwords in cookies.
- An API can return JSON rather than a rendered page, allowing another website or application to consume structured results from the same Flask service.
Chapters
- CS50 Week 9 applies earlier course concepts to server-side web programming.
- Flask combines Python logic with HTML and SQL to build complete web applications.
- The same foundations can support mobile apps through web-based services.
- A static server such as http-server serves files and folders, while Flask maps URL routes to Python functions.
- Flask is a microframework that handles common tasks such as parsing GET and POST requests.
- The conventional project setup includes app.py and a requirements.txt file listing dependencies.
- Import Flask, create an app object, and associate a function with a URL using @app.route.
- The route '/' serves the homepage, and its function can return plain text or HTML.
- Running flask run starts the development server, typically on port 5000.
- Returning a long HTML string from Python works but mixes presentation with application logic.
- Flask's render_template function loads HTML from a conventionally named templates directory.
- Separating app.py from templates makes pages and server logic easier to maintain.
- Flask exposes GET query parameters through request.args, such as the name in /?name=David.
- Pass values to render_template as named arguments, then insert them in HTML with Jinja's double-brace syntax.
- The rendered value appears in the HTML sent by the server, rather than being added later by client-side JavaScript.
- Directly accessing a missing request.args key can produce an HTTP 400 error.
- Python can test whether a key exists, or request.args.get("name", "world") can supply a default.
- A present but empty parameter differs from a missing parameter, so validation may need to check the value too.
- An HTML form with method GET and a named input submits the user's value as a query parameter.
- The form's action can target a Flask route such as /greet, which renders greet.html.
- A missing template produces a server-side error visible in Flask's terminal, while the browser gets a generic error page.
- Separate index.html and greet.html initially duplicate the document structure and other boilerplate.
- A shared layout.html defines common HTML and a Jinja block named body.
- Child templates use extends and fill the body block, keeping each page focused on its unique content.
- GET places form fields in the URL, making it useful for searches and shareable links.
- POST sends fields in the request body, keeping them out of the URL but not hidden from browser developer tools or network observers.
- Flask routes default to GET; POST handlers must allow the POST method and read fields from request.form.
- A single Flask route can accept both GET and POST and branch on request.method.
- GET can render the form, while POST processes the submitted name and renders the greeting.
- Jinja supports conditional logic such as if and else, allowing templates to choose a fallback like “world.”
- The Frosh IMs example replaces paper sports sign-up forms with a web registration flow.
- The prepared Flask project separates app.py, requirements.txt, templates, and static assets.
- A viewport meta tag helps pages scale to mobile screen widths.
- The registration form sends a student's name and selected sport to /register using POST.
- An HTML select menu offers Basketball, Soccer, and Ultimate Frisbee as controlled choices.
- A blank, selected default option avoids accidentally registering a student for the first sport.
- The /register route reads submitted values from request.form and checks for both a name and a sport.
- Missing information can render a failure.html template; valid submissions can render a success page.
- Flask's terminal traceback helps diagnose template syntax errors that appear to users as generic HTTP 500 responses.
- Browser developer tools let a user modify the select menu and submit an unoffered sport such as volleyball.
- Client-side HTML controls are not security boundaries, so Flask must validate submitted sports on the server.
- Checking a sport against an approved list prevents unexpected values from being accepted.
- A global SPORTS list centralizes the allowed choices and avoids duplicating sport names across Python and HTML.
- Pass SPORTS into index.html and use a Jinja for loop to generate each option.
- Radio buttons with the same name are mutually exclusive, and the server can read their selection through request.form.
- An error.html template can display a message passed from Flask as a Jinja variable.
- Separate checks identify a missing name, missing sport, or sport not present in SPORTS.
- Specific messages such as “missing sport” and “invalid sport” help users correct their submissions.
- A Python dictionary can temporarily map each student's name to their selected sport.
- A /registrants route passes that dictionary to a Jinja template that loops over entries to create table rows.
- This approach loses all registrations when the Flask process restarts, making it unsuitable for persistent records.
- The example replaces the volatile dictionary with froshims.db and a registrants table containing ID, name, and sport.
- CS50's SQL library executes parameterized INSERT and SELECT queries to write and retrieve registration rows.
- The Jinja table iterates over the returned list of dictionaries, and records remain after Flask restarts.
- A database ID uniquely identifies a row, unlike a name that multiple students may share.
- Each table row can include a POST form with a hidden ID field and a deregister button.
- The /deregister route uses a parameterized DELETE query and redirects back to /registrants.
- GET requests should not trigger destructive actions: a forged link could otherwise cause a supervisor to delete a registration by clicking it.
- POST requires a form submission and is a more appropriate method for database changes, though it does not itself provide privacy or protection from forged requests.
- Flask serves images, CSS, and JavaScript from a static directory; templates are loaded separately from templates.
- Changing radio inputs to checkboxes lets a student select multiple sports.
- Flask's request.form.getlist("sport") retrieves all submitted values, which must each be checked against SPORTS.
- The example inserts one registration row per selected sport, creating duplicate student names and motivating a separate student table.
- The lesson frames app.py as controller or business logic, Jinja templates as views, and SQLite data as the model.
- This Model-View-Controller structure separates application behavior, user-facing HTML, and persistent data.
- The boundaries are not absolute, since templates can also contain Jinja variables, loops, and conditionals.
- HTTP requests are generally stateless, so a server needs a mechanism to recognize a returning browser.
- A cookie is a key-value pair exchanged through Set-Cookie and Cookie headers, often carrying a session identifier rather than a password.
- A session associates server-side key-value data with a user, enabling features such as persistent login and shopping carts.
- Flask-Session provides a per-user session dictionary, and the example stores a submitted name under session["name"].
- The homepage uses Jinja conditionals to show either “not logged in” or the user's name and a logout link.
- Logging out with session.clear removes the session data; the demo uses usernames only, while real login systems also require passwords and security measures.
- The store example uses store.db to list five books, including The Hitchhiker's Guide to the Galaxy.
- Each book has a POST form with a hidden ID, allowing an Add to Cart button to submit the selected book.
- The session stores a cart list of book IDs, and a SQLite query retrieves those books for cart.html.
- The shows example queries shows.db from a search route and renders matching titles in search.html.
- A basic title match can find entries such as “The Office” only when the query matches the stored title as expected.
- Jinja loops turn database results into HTML list items.
- SQL LIKE supports partial matches, so a query can find titles containing a phrase rather than requiring an exact match.
- Percent wildcards before and after the user's query allow text such as “The Office” to match within a longer title.
- Parameterized SQL keeps the user query separate from the SQL statement.
- An API exposes data through HTTP routes so other applications can use it without receiving a full webpage.
- The shows search examples progress from returning HTML fragments to returning structured JSON data.
- Flask's jsonify converts Python database results into JSON, a format commonly consumed by JavaScript and other clients.
- Flask brings together Python, HTML, SQL, HTTP methods, templates, and browser-side JavaScript from earlier CS50 weeks.
- The lesson encourages applying these building blocks in a final project, including web or mobile applications.
- The lecture closes by pointing students toward the next CS50 week.
Transcript excerpt
0:43 De acuerdo. Esto es CS50. Esta ya es la semana 9. Y me atrevo a decir que esta semana es la más representativa de lo que harán después de la clase si eligen programar en el futuro y abordar algún proyecto que sea nuevo para ustedes. De hecho, lo más parecido a esta semana fue quizás la semana 6, en la que realmente no introdujimos tantos conceptos nuevos, sino que los tradujimos de C a Python. Y así, esta semana en particular, el objetivo es sintetizar realmente las últimas 10 semanas de clase, aprovechando muchos de los componentes básicos que, con suerte, ahora están metafóricamente en su caja de herramientas y les brinda la oportunidad de aplicar esas ideas a nuevos problemas, en particular, la programación web. Así que todos los días, ustedes y yo estamos usando la web de alguna forma. Todos los días, ustedes y yo estamos usando aplicaciones móviles de alguna forma. Y dijimos la semana pasada que los lenguajes que subyacen a muchas de esas aplicaciones son HTML y JavaScript para el diseño y la
1:32 estética, y luego también en parte JavaScript para gran parte de la interactividad del lado del cliente que podrían experimentar hoy en día. Bueno, hoy cerramos el círculo y traemos de vuelta un componente del lado del servidor mediante el cual volveremos a escribir algo de Python, volveremos a escribir algo de código SQL y lo usaremos para crear nuestras propias aplicaciones web completas. Y a su vez, si así lo desean, aplicaciones móviles también para su proyecto final. Así que hasta ahora, cuando hacíamos algo con la web, ejecutaron este comando la semana pasada, http-server, que literalmente hizo exactamente eso. Generó un llamado servidor HTTP. Es decir, un servidor web cuyo propósito en la vida es simplemente servir contenido desde, por ejemplo, su carpeta
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.