Introduction to Computer Science: Web Programming Using Flask by Harvard’s CS50 (2018)

Posted by


Flask is a lightweight framework for web development in Python. In this tutorial, we will cover the basics of web programming with Flask, as taught in Harvard’s CS50 course. This tutorial assumes you have a basic understanding of Python and some knowledge of web development.

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

pip install Flask

Once you have Flask installed, you can start building your web application. Create a new Python file, for example, app.py, and open it in your favorite code editor. In this file, you will define your Flask application.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

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

In this code snippet, we imported the Flask class from the flask module and created a new instance of the Flask class, called app. We then defined a route for the root URL (‘/’). When a user accesses this URL, the index() function is called, which returns the message ‘Hello, World!’. Finally, we run the Flask application with debug mode enabled.

To run your Flask application, simply execute the app.py file in your terminal:

python app.py

You should see a message indicating that the Flask application is running. Open a web browser and navigate to http://127.0.0.1:5000/ to see your web application in action.

Flask uses routes to map URLs to view functions, which generate HTTP responses. You can define routes with variable parts:

@app.route('/hello/<name>')
def hello(name):
    return f'Hello, {name}!'

In this example, the route /hello/ accepts a variable part called name, which is passed as an argument to the hello() function.

Flask also supports HTTP methods, such as GET and POST. You can specify the allowed methods for a route using the methods parameter:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return 'Login successful'
    return 'Please log in'

In this code snippet, the login() function accepts both GET and POST requests. If the request method is POST, the function returns ‘Login successful’. Otherwise, it returns ‘Please log in’.

Flask templates allow you to separate the presentation logic from the application logic. Create a new directory called templates in your project directory and add a new HTML file, for example, index.html:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
</body>
</html>

In your app.py file, you can render this template with the render_template() function:

from flask import render_template

@app.route('/hello/<name>')
def hello(name):
    return render_template('index.html', name=name)

In this example, we pass the name variable to the index.html template, which is rendered with the value of the name variable.

Flask also supports URL building, which allows you to generate URLs based on the route name:

@app.route('/profile')
def profile():
    return 'User profile'

@app.route('/user/<username>')
def user(username):
    return f'{username}'

In the index.html template, you can use the url_for() function to generate the URL for a specific route:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>
    <a href="{{ url_for('profile') }}">Profile</a>
</body>
</html>

In this tutorial, we covered the basics of web programming with Flask, including defining routes, handling HTTP methods, using templates, and URL building. Flask provides a simple and flexible framework for building web applications in Python. Experiment with these concepts and explore more advanced features of Flask to create dynamic and interactive web applications. Good luck with your web development journey!

0 0 votes
Article Rating

Leave a Reply

31 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@freecodecamp
13 days ago

This is the eighth video in the course. Check out the full playlist: https://www.youtube.com/playlist?list=PLWKjhJtqVAbmGw5fN5BQlwuug-8bDmabi
Here is a forum to discuss CS50 with other people from freeCodeCamp: https://www.freecodecamp.org/forum/c/harvard-cs50

@will_strong_forme
13 days ago

This’s a great teacher of Harvard! Thank Harvard’s for the free source.

@DKSorg
13 days ago

Completed the CS50 Intro this May, just Lectures…. Big help in understanding the Lager concepts in order to better understand more niche Youtube Videos and actually understanding what is happening and how, but also being able to troubleshoot and correct.
-> Just started a project that requires Flask.

@sonamohialdin3376
13 days ago

Excellent teaching

@jean-michelbendaci2564
13 days ago

Thanks David.
Satya Nadella blackmailed and active corrupt.

@DesignsbyBlanc
13 days ago

David's amazing!

@tutujnrlangat
13 days ago

Wow it's so amazing,I found it interesting,I guess it's the right time I got it since am still learning it,,and can I get documentation for this course also,

@joer4227
13 days ago

How come when he showed how to handle the arguments in the url did his hello david, hello world work before he type the code to make it work

@piyiotisc
13 days ago

Thanks for this lectures. The professor is amazing

@voulieav
13 days ago

I wish this guy was the teacher at uni – i wouldnt have dropped out of software engineering.

@malikqatagan8977
13 days ago

Better version than newer ones

@tielessin
13 days ago

What a great teacher!

@Nasengold
13 days ago

incredible teacher

@guenzburghdcl7637
13 days ago

This is dated in 2022, dont bother

@conservativestrawman9837
13 days ago

flask run does not work in the codespace.

I have had literally no issues at all learning everything in this class.

Week 9: lol git gud noob

why can I not run flask? I'm not even 20 min into the vid and its been hours of searching google with no solutions to be found.

really glad I threw money at this thinking I could avoid manual labor for once.

@liamwelsh5565
13 days ago

1:23:19 Probably the only wrong thing in this video. "Not sure what this does? Just run it!" lmao

Other than that, the fact that you can get such a high-quality course online for free is unbelievable to me. I can assure you that the intro to CS course you take at your local college, the one you pay hundreds or thousands of dollars for does not come close to this.

@brothermalcolm
13 days ago

@14:35 flask hello world
give me access to the library
turn my file into a web app
listen to get requests on /

@SUGATORAY
13 days ago

1:30:20 The instructor said that you cannot indent in a list comprehension (only use a list-comprehension when it fits within the screen). This is not true.
Since the list comprehension is wrapped within a pair of brackets [ ], you can break the line anywhere you prefer to facilitate enhanced readability; and the list comprehension will work perfectly fine. Although, a really long list-comprehension that requires one to break down into multiple lines, may not be desirable, as future maintenance of such code could elicit unnecessary confusion. One of the tenets of writing better code is also the how less cryptic it is for future maintenance.
Also, request.args.get("q") is getting called as many times as the number of words in WORDS variable. Perhaps a more resource-conserved approach will be this:

q = request.args.get("q")
words = [ word for word in WORDS if word.startswith(q) ]

@osiris5449
13 days ago

his energy… a f*cking chapel? 😂 I cant.

@tcgvsocg1458
13 days ago

can some one ask him to stop jumping?

31
0
Would love your thoughts, please comment.x
()
x