Serving Static Files with Flask

Flask Tip - Static Files

Flask automatically creates a static endpoint to serve static files (like HTML templates, CSS stylesheets, JS files, and images).

For example, to serve an image, copy the image into the "static" folder of the Flask project. Create a new route and navigate to


from flask import current_app

def flask_logo():
    return current_app.send_static_file('flask-logo.png')

Get a list of all routes defined in a Flask app

Flask Tip - Flask Routes Command

To easily see all the routes defined in a Flask application, use the routes command.


$ flask routes

Endpoint  Methods  Rule
--------  -------  -----------------------
index     GET      /
static    GET      /static/<path:filename>

Adding Automatic Imports to the Flask Shell

Flask Tip:

Additional automatic imports can be added to the Flask shell using shell_context_processor().


# ... After creating the Flask application (`app`) ...
def shell_context():
    return {'database': database}

# in terminal
$ flask shell
>>> print(database)

Prototyping with the Flask Shell

Flask Tip - Flask Shell

Prototyping with the Python interpreter is really beneficial with a Flask application too!

Start the Python interpreter with the Flask application loaded to prototype with it.


$ flask shell
>>> print(app.url_map)
>>> print(app.blueprints)

CSRF Protection in Flask with Flask-WTF

Flask tip:

You can use Flask-WTF to implement CSRF protection for your application.


from flask import Flask, Response, abort, redirect, render_template, request, url_for
from flask_login import (
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)

login_manager = LoginManager()

csrf = CSRFProtect()


You can read more here:

Flask - async and await

Flask tip:

With Flask >= 2.0 you can create asynchronous route handlers using async/await.


import asyncio

async def async_get_data():
    await asyncio.sleep(1)
    return "Done!"

async def get_data():
    data = await async_get_data()
    return data

Want to learn more? Check out Async in Flask 2.0.

Calculate the execution time of Flask views

Did you know?

You can use a decorator to time the execution of Flask views.

For example👇

from functools import wraps
from timeit import default_timer

def timer(f):
    def wrapper(*args, **kwargs):
        start_time = default_timer()
        response = f(*args, **kwargs)
        total_elapsed_time = default_timer() - start_time
        response += f"<h3>Elapsedtime: {total_elapsed_time}</h3>"
        return response

    return wrapper

def hello_world():
    return "Hello World!"

How can I implement a custom error handler in Flask?

Did you know?

You can register exception handlers to a Flask app based on an exception class or response status code.

An example👇

from flask import Flask, jsonify, abort

app = Flask(__name__)

class ValidationException(Exception):
    code = 500
    message = "Unknown error"

def handle_validation_exception(exc):
    return (
        jsonify({"msssage": exc.message, "exception": exc.__class__.__name__}),

def handle_internal_server_error(exc):
    return jsonify({"msssage": "Oops!", "exception": "Internal server error"}), 500

def hello():
    raise ValidationException()

Flask Sentry Example

Flask tip:

Add Sentry to your Flask app to track unhandled exceptions.

An example👇

import sentry_sdk
from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration


app = Flask(__name__)

Managing session data in Flask

Flask tip:

Setting a value to Flask's session is as simple as:

session['key'] = 'value'

For example:

from flask import Flask, redirect, request, session, url_for

# Create the Flask application
app = Flask(__name__)

app.secret_key = "BAD SECRET KEY"

@app.route("/set_email", methods=["GET", "POST"])
def set_email():
    if request.method == "POST":
        # Save the form data to the session object
        session["email"] = request.form["email_address"]
        return redirect(url_for("set_email"))
    return """
        <form method="post">
        <label for="email">Enter your email address:</label>
        <input name="email_address" required / >
        <button type="submit">Submit</button