CS50x 2023 – Lecture 9 – Flask Tutorial
In Lecture 9 of CS50x 2023, we will be learning about Flask, a popular web framework for Python. Flask is a lightweight and modular micro-framework that provides the necessary tools to build web applications quickly and easily. In this tutorial, we will cover the basics of Flask and demonstrate how to create a simple web application using Flask.
Prerequisites:
Before starting this tutorial, make sure you have Python installed on your computer. You can download Python from the official website (https://www.python.org/downloads/). Additionally, you will need to install Flask by running the following command in your terminal:
pip install Flask
Creating a Flask Application:
To create a new Flask application, create a new directory for your project and navigate to it in your terminal. Inside the project directory, create a new Python file, for example, app.py
, and open it in a text editor of your choice.
Importing Flask:
In the app.py
file, import Flask by adding the following line of code at the top of the file:
from flask import Flask
Initializing the Flask App:
Create a new instance of the Flask class by adding the following code in the app.py
file:
app = Flask(__name__)
Defining Routes:
In Flask, a route is a URL that is mapped to a specific function. To define a route in Flask, use the @app.route()
decorator. For example, to create a route for the home page, add the following code in the app.py
file:
@app.route('/')
def home():
return 'Hello, World!'
Running the Flask App:
To run the Flask app, add the following code at the bottom of the app.py
file:
if __name__ == '__main__':
app.run()
Save the app.py
file and run the Flask app by executing the following command in your terminal:
python app.py
You should see output similar to the following:
* Running on http://127.0.0.1:5000/
Open a web browser and navigate to http://127.0.0.1:5000/
to see the "Hello, World!" message displayed on the home page.
Congratulations! You have successfully created a simple web application using Flask. Feel free to explore more features and functionalities of Flask to build more complex web applications. Flask provides a wide range of tools and extensions that can help you create powerful and dynamic web applications with ease. Have fun coding with Flask!
Came here after many years of studying/working in this field. This lecture is great, but I promise you, you DON'T NEED TO PAY a university to teach you this. I learned this and MUCH more by myself, using youtube tutorials and free PDF's.
Thank you, David.
Anyone else's POST method not work?
Tried everything myself….
🎯 Key Takeaways for quick navigation:
01:12 📚 CS50 week nine focuses on synthesizing various programming languages and techniques into web programming, emphasizing the culmination of past weeks' learning.
03:37 🌐 The lecture introduces the transition from static content with HTML/CSS to dynamic content with JavaScript and then to server-side programming using Flask in Python.
08:48 🐍 Flask is introduced as a Python framework for web development, and Jinja is mentioned as a syntax for placeholders in web pages.
09:46 📁 Conventions for Flask include having an `app.py` file, a `templates` folder for HTML files, and optionally a `static` folder for static content like images and CSS.
13:34 ⚙️ Flask's basic structure involves creating a Flask application, defining routes using decorators, and implementing functions to handle different routes.
18:20 🔄 The lecture demonstrates handling HTTP parameters from the URL using Flask's `request.args` to dynamically personalize content on the web page.
22:04 🔄 Flask uses Jinja syntax for templates, where variables are enclosed in double curly braces, like `—`.
23:55 📤 The `render_template` function in Flask takes the name of the template and additional placeholders, allowing dynamic content in HTML files.
26:19 🚀 The `GET` function in Flask's `request.args` can be used to retrieve values from the query string, and it includes an optional default value.
31:26 📁 Using a common layout template in Flask helps avoid redundancy by extending it in other templates using the `{% extends "layout.html" %}` syntax.
40:08 🌐 Creating a layout template in Flask allows you to maintain a consistent structure across multiple pages, improving code organization and reducing redundancy.
43:00 🌐 When designing web apps, be cautious about sensitive information, like passwords, appearing in the URL. Using POST instead of GET for forms involving sensitive data is recommended.
44:25 📬 Changing the form method from GET to POST helps enhance privacy and security, preventing sensitive data from being exposed in the URL.
46:47 🕵️♂️ POST requests hide submitted data below HTTP headers, providing additional privacy compared to GET requests. Adjusting both HTML form and Flask route to use POST is essential.
48:15 🛠️ Developer tools in browsers, like Chrome's Network tab, allow you to inspect and understand the data being sent between the browser and the server, aiding in debugging and development.
50:34 🚀 Combining multiple routes into one can simplify the structure of your web app. In Flask, using the same route for different HTTP methods (GET and POST) is possible and can help manage complexity.
51:58 🤖 Request arguments differ for GET and POST in Flask. For GET, it's `request.args`, while for POST, it's `request.form`. Be mindful of this when handling form data in your Flask app.
55:19 🔄 Reloading a page with form resubmission warnings is common when dealing with POST requests. Chrome provides these warnings to prevent accidental duplicate submissions.
58:41 🌐 Demonstrating the creation of a simple web app for registering for sports. HTML forms with Flask routes can capture user data and process it in the backend.
01:02:06 📝 When creating a dropdown menu title equivalent, use a disabled option that's automatically selected called "Sport" to prevent manual selection but still display it at the top.
01:03:01 🚧 If encountering a 404 error in Flask, check if the route exists, and ensure you've included the `@app.route` decorator and the corresponding function.
01:04:00 📄 When creating multiple pages, use a common layout template to avoid redundancy, and utilize the `extends` keyword to inherit from the layout in child templates.
01:07:46 📝 To enable support for the POST method in a Flask route, use `methods=["POST"]` in the `@app.route` decorator.
01:08:43 🗄️ Store user registrations in a dictionary in the computer's memory, with the student's name as the key and the sport they registered for as the value.
01:12:55 🔄 Use Jinja syntax for loops in HTML templates to iterate over a dictionary and display its content dynamically.
01:17:40 🐛 Be cautious about variable and function naming conflicts, as they can lead to unexpected errors. Capitalize global variables to distinguish them clearly.
01:19:34 🤔 *When working with a `
47:10 Why isn't the output, hello, David?
Masterclass!
absolutely amazing!!!
Just completed CS50 Finance, and damn it feels good. Thanks the CS50 team for these amazing Lectures and Problem sets!!
The exercise at 45:58 needed to change second parameter of render_template to either request.form for form data or request.get_json() for JSON data to be able to get the data.
Was so funny to see the cart of cookies 😂😂
This is more than teaching, to me, this is a very good form of philanthropy
Thank you Dr/ David you are the best for me
What I've searched, read throughout the years and piecing things together could have be done simply by watching a 2 hours video. Fantastic video!!! ✅
At 1:09:54; where did the sport came from when assigning to variable. I know the name is there because it's the value given to input's name attribute but I don't see the sport anywhere.
Edit: Explained at 1:18:08; wasted couple of minutes going back and fourth until he explained it. BTW feeling great on picking it up.
Bug at 47:03 ("hello, world" vs "hello, David" is explained at 53:44.
With 'get' method, use 'request.args.get'. With 'post' method, use 'request.form.get' instead
guy is an absolute legend
Wow, once again it has been a master class… Thank you David, your way of teaching is inspiring… With you high quality education is safe… 💯
"You are not going to be pleased with this syntax." – David J. Malan
This mf explains the lesson brilliantly
Ohh that's what Incognito mode is for… Think I may have been misusing that feature thus far.