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 http://127.0.0.1:5000/logo.

👇

from flask import current_app

@app.route('/logo')
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`) ...
@app.shell_context_processor
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.

Example:

from flask import Flask, Response, abort, redirect, render_template, request, url_for
from flask_login import (
    LoginManager,
    UserMixin,
    current_user,
    login_required,
    login_user,
    logout_user,
)
from flask_wtf.csrf import CSRFProtect

app = Flask(__name__)
app.config.update(
    DEBUG=True,
    SECRET_KEY="secret_sauce",
)

login_manager = LoginManager()
login_manager.init_app(app)

csrf = CSRFProtect()
csrf.init_app(app)

...

You can read more here: https://testdriven.io/blog/csrf-flask/.

Flask - async and await


Flask tip:

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

Example:

import asyncio


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


@app.route("/data")
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):
    @wraps(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


@app.route("/")
@timer
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"


@app.errorhandler(ValidationException)
def handle_validation_exception(exc):
    return (
        jsonify({"msssage": exc.message, "exception": exc.__class__.__name__}),
        exc.code,
    )


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


@app.route("/")
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

sentry_sdk.init(
    dsn="your-sentry-dsn",
    integrations=[FlaskIntegration()],
    traces_sample_rate=0.3,
    environment="production",
)

app = Flask(__name__)

Managing session data in Flask


Flask tip:

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

session['key'] = 'value'

https://testdriven.io/blog/flask-sessions/

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"]
        print(session["email"])
        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
        </form>
        """