CS50 Cheatsheet for Flask

Flask Basics

What is Flask?

Flask is a lightweight and flexible web framework that allows you to build web applications quickly and easily. It is a great tool for building web applications, APIs, and more.

Directory Structure

When you create a Flask application, you will typically have the following directory structure:

myapp/
    app.py
    static/
        styles.css
    templates/
        index.html
    requirements.txt

Installation

To install Flask, you can use pip:

pip install Flask

In CS50’s Codespaces IDE, you will need to include the following in your requirements.txt file:

Flask

Hello World

Here’s a simple “Hello, World!” example in Flask:

from flask import Flask

app = Flask(__name__)

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

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

Running Your Flask App

To run your Flask app, you can use the following command:

python app.py

In CS50’s Codespaces IDE, you can just use flask run.


Routes

Routes are the URLs that your application listens for. You can define routes using the @app.route decorator.

@app.route('/')
def index():
    return 'Index Page'

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

Variable Routes

You can use variable routes to pass variables to your routes.

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


Templates

What are Templates?

Templates allow you to separate your HTML from your Python code. You can use the render_template function to render templates.

from flask import render_template

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

Jinja Templating

Jinja is a templating engine for Python. You can use Jinja to include variables, loops, and conditionals in your templates.

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

In your Python code, you can pass variables to your template like this:

@app.route('/')
def index():
    return render_template('index.html', title='Home', name='Alice')

This will render as:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>Hello, Alice!</h1>
</body>
</html>

Layouts

You can use layouts to create a consistent look and feel across your application. You can use the extends and block tags to create layouts.

<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

In your template, you can extend the layout like this:

{% extends "layout.html" %}

{% block title %}Home{% endblock %}

{% block content %}
    <h1>Welcome to my website!</h1>
{% endblock %}


Forms and Requests

Forms in HTML

Forms allow users to input data into your application. In your templates, you can use the form tag to create forms.

<form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

Handling Form Data in Flask

You can use the request object to access form data in Flask.

from flask import request

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        return 'You have logged in!'
    else:
        return 'Please log in'

GET vs. POST Requests

GET requests are used to request data from a server, while POST requests are used to submit data to a server. You can use the request object to access data from both types of requests.

from flask import Flask, render_template, request

app = Flask(__name__)

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

@app.route("/greet", methods=["POST"])
def greet():
    return render_template("greet.html", name=request.form.get("name", "world"))


SQL / SQLite3

Accessing Databases in Flask

Flask can be used with SQL databases such as SQLite3. You can use the sqlite3 module to interact with SQLite3 databases.

from flask import Flask, render_template, request
from CS50 import SQL

app = Flask(__name__)

db = SQL("sqlite:///database.db")

@app.route("/")
def index():
    rows = db.execute("SELECT * FROM users")
    return render_template("index.html", rows=rows)

Executing SQL Queries

You can use the execute method to execute SQL queries in Flask.

@app.route("/add", methods=["POST"])
def add():
    name = request.form.get("name")
    db.execute("INSERT INTO users (name) VALUES (?)", name)
    return redirect("/")


Cookies and Sessions

Cookies

Cookies are small pieces of data that are stored on the client’s computer. You can use the set_cookie and get_cookie methods to set and get cookies in Flask.

@app.route("/")
def index():
    resp = make_response(render_template("index.html"))
    resp.set_cookie("username", "alice")
    return resp

Sessions

Sessions allow you to store user data across requests. You can use the session object to store and access session data in Flask.

In HTML, you might have a login form like this:

{% extends "layout.html" %}

{% block body %}

    <form action="/login" method="post">
        <input autocomplete="off" autofocus name="name" placeholder="Name" type="text">
        <button type="submit">Log In</button>
    </form>

{% endblock %}

Then, in your Python code, you can handle the login form like this, storing the user’s name in the session:

from flask import Flask, redirect, render_template, request, session
from flask_session import Session

# Configure app
app = Flask(__name__)

# Configure session
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)


@app.route("/")
def index():
    return render_template("index.html", name=session.get("name"))


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        session["name"] = request.form.get("name")
        return redirect("/")
    return render_template("login.html")


@app.route("/logout")
def logout():
    session.clear()
    return redirect("/")