Flask Lecture in CS50x 2024: Session 9

Posted by


CS50x 2024 – Lecture 9: Flask

In Lecture 9 of CS50x 2024, we will be diving into Flask, a popular web framework for Python. Flask allows developers to quickly create web applications using Python and is known for its simplicity and flexibility. In this tutorial, we will cover the basics of Flask, including how to set up a basic Flask application, handle routes, templates, and forms.

Setting Up Flask
To get started with Flask, you will first need to install it on your machine. You can do this using pip, the Python package manager. Open your terminal and run the following command:

pip install Flask

This will install the Flask package on your machine. Once Flask is installed, you can start creating your first Flask application.

Creating a Basic Flask Application
Create a new directory for your Flask application and navigate into it. Inside this directory, create a new Python file, for example, app.py. Open this file in a text editor and start by importing the Flask module:

from flask import Flask

Next, create an instance of the Flask class:

app = Flask(__name__)

We have now created a basic Flask application. Let’s add a route to this application.

Handling Routes in Flask
Routes in Flask define the URL paths that your application will respond to. For example, if a user visits http://localhost:5000/, we may want to display a welcome message. To add a route to your Flask application, use the @app.route() decorator:

@app.route('/')
def index():
    return 'Welcome to my Flask application!'

In this example, we have defined a route for the root URL path / that will display a welcome message when visited.

Running the Flask Application
To run your Flask application, add the following code at the bottom of your app.py file:

if __name__ == '__main__':
    app.run(debug=True)

Save your app.py file and run it in your terminal:

python app.py

You should see output indicating that your Flask application is running. Visit http://localhost:5000/ in your web browser to see your welcome message.

Handling Templates in Flask
In a real web application, you would want to separate your application logic from your HTML templates. Flask allows you to render HTML templates using its render_template function. First, create a templates directory inside your Flask application directory. Inside this directory, create a new HTML file, for example, index.html. In this file, you can write your HTML content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to my Flask application!</h1>
</body>
</html>

To render this template in your Flask application, import the render_template function and modify your route handler:

from flask import render_template

...

@app.route('/')
def index():
    return render_template('index.html')

Now, when you visit http://localhost:5000/, your Flask application will render the index.html template.

Handling Forms in Flask
In a web application, you often need to handle user input through forms. Flask provides a request object to access form data submitted by the user. For example, let’s create a simple form that allows users to enter their name. Create a new HTML file, for example, form.html, inside the templates directory:

<!DOCTYPE html>
<html>
<head>
    <title>Enter Your Name</title>
</head>
<body>
    <form action="/" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

In your app.py file, modify your route handler to handle form submissions:

...

from flask import request

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.form['name']
        return f'Hello, {name}!'
    return render_template('form.html')

Now, when a user submits the form on http://localhost:5000/, the application will display a personalized message based on the user’s input.

Conclusion
In this tutorial, we have covered the basics of Flask, a web framework for Python. We have learned how to set up a basic Flask application, handle routes, templates, and forms. Flask is a powerful tool that allows developers to quickly create web applications using Python. If you are interested in web development with Python, Flask is an excellent framework to explore further. Happy coding!

0 0 votes
Article Rating
22 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@SMD-kk8ud
3 months ago

Just….Awesome!!

@user-td4pf6rr2t
3 months ago

1:03:55 can't you use base64 and assign an id to get Sports in hex and css the id tag?

@e.n85784
3 months ago

I wonder if Yale will add the term "boilerplate" to their Bingo card

@lionking2592
3 months ago

🎉 completed. This is awesome intro for flask begginers. THANK YOU 🙏🙏

@swampguy277
3 months ago

the DDB moment was so damn funny hahah

@duydangdroid
3 months ago

Duck >> Stack Overflow > glance at the audience for help

@quang.luu.179
3 months ago

👍👍👍

@chrisjoyce4047
3 months ago

Continuing the lecture I see he fixed the request.form.getlist problem, but the second problem remains.

@chrisjoyce4047
3 months ago

There are two problems with the code presented in the lecture in the froshims section. Firstly, David's code uses request.form.getall which does not work in the current CS50 ide. You need to use request.form.getlist instead. Secondly, "Ultimate Frisbee" gives an error when a loop is used to check the sports with {{sport}}. To make it work you need to use "{{sport}}" instead.

@thetasworld
3 months ago

And I thought week 8 was tough…good lord.

@01juniorpen
3 months ago

01:40:00

@rafiullah-zz1lf
3 months ago

🎉🎉🎉🎉 feeling happy finally got finance done and got 21 /21. Thanks @david J.Malan

@UnboxRacing
3 months ago

"Let me go ahead and PROPOSE that…." Bingo! Classic David. I wish we had Profs like DM when I was at school.

@UnboxRacing
3 months ago

If you are following this at home your won't have access to the same environment as David. Advisable to create virtual environment in 'hello' and run flask that way. Django would have been nice but DM's teaching is world class.

@caiofernando
3 months ago

I have a question about the last bit of this lecture.
Since he got rid of the template search.html and just returned the jsonified list of shows, at what point does the json file get iterated over and converted into a list with the titles of the movies? I'm assuming version 3 of shows has an extra piece of code at index.html that does that, right?

@-.lucas.vieira.-
3 months ago

If something like "this is a lot to process" hits you after watching the lecture, I can say, assertively, you are not alone.

@teaganp5011
3 months ago

I’m really thankful for this class. It really feels like I am part of the class and that duck debugger moment get so relatable

@Svish_
3 months ago

Really wish you would've introduced the label tag, instead of using the placeholder-attribute, which is kind of terrible for multiple UX and accessibility reasons 😟

@xiuzhenyang8047
3 months ago

Anyone know how to open a terminal after I accidentally close all the terminal?