Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 72 ยท Structure and Configuration

Blueprints

Learn how Flask blueprints split an app into modules: url_prefix, endpoint names like blog.index, blueprint templates and static files, and error handlers.

A single app.py with fifteen routes is fine. With a hundred routes covering a blog, an admin area, a JSON API and a shop, it turns into a wall of code where nobody can find anything. Blueprints are Flask's way of splitting an application into self-contained parts.

A blueprint is a bundle of routes, error handlers, templates and static files that is defined on its own and later registered on an app. The blueprint does nothing until you register it, and you can register it with a different URL prefix, or even more than once. In this lesson you will create blueprints, see how their endpoints get a name prefix, share templates and static files, and handle errors per blueprint or for the whole app.

Creating and registering a blueprint

You create a Blueprint with a name and an import name, then decorate functions with the blueprint's own route instead of app.route. In the app (usually inside the factory from the previous lesson), you call app.register_blueprint().

flowchart TD
    APP["Flask app"] --> BLOG["blog blueprint<br/>url_prefix /blog"]
    APP --> API["api blueprint<br/>url_prefix /api/v1"]
    APP --> ADMIN["admin blueprint<br/>url_prefix /admin"]
    BLOG --> R1["blog.index, blog.show"]
    API --> R2["api.posts, api.health"]
    ADMIN --> R3["admin.dashboard"]

Each blueprint owns a group of routes. The app only knows how to mount them.

The example below defines two blueprints and registers both. Look closely at the endpoint names in the printed URL map: each is prefixed with its blueprint's name.

Python Two blueprints with prefixes and endpoint names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Here is what to take from the output:

  • url_prefix is put in front of every route of the blueprint. The route "/" in blog became /blog/. The prefix can be given on the Blueprint(...) call or, overriding it, on register_blueprint(..., url_prefix=...).
  • Endpoints are blueprint_name.function_name. The view index in the blog blueprint has the endpoint blog.index. Two blueprints can therefore both have a function called index without clashing, which is a big reason to use them.
  • url_for needs the full endpoint from outside the blueprint (url_for("blog.index"), as the API does). Inside a blueprint's own views and templates you can use the dot shortcut: url_for(".show", post_id=3) means "the show endpoint of the current blueprint". This is how the next: URL was built.
  • The slash matters. The rule is /blog/, so a request for /blog gets a redirect (status 308) to the version with the slash, just as in Routes and HTTP Methods.

Blueprint names must be unique within an app, and they must not contain a dot, because the dot separates the blueprint from the view name in endpoints.

Where the code lives

Most projects give every blueprint its own package:

TEXT
myapp/
    __init__.py            # create_app()
    blog/
        __init__.py        # bp = Blueprint("blog", __name__, ...)
        routes.py          # from . import bp, then the views
        templates/
            blog/
                index.html
                post.html
        static/
            blog.css
    api/
        __init__.py
        routes.py

Create bp in the package's __init__.py, and import routes at the bottom of it so the decorators run. Then the factory imports the blueprint and registers it:

Python
def create_app(config=None):
    app = Flask(__name__)
    ...
    from .blog import bp as blog_bp
    from .api import bp as api_bp
    app.register_blueprint(blog_bp)
    app.register_blueprint(api_bp, url_prefix="/api/v1")
    return app

Templates and static files

A blueprint can carry its own template_folder and static_folder, given as paths relative to the blueprint's package:

Python
bp = Blueprint("blog", __name__, template_folder="templates", static_folder="static")

Template lookup works like this: Flask first searches the application's templates folder, then the folders of each registered blueprint in registration order. All of these folders are merged into one namespace. That has a consequence worth remembering: if two blueprints both contain index.html, the first one found wins and the other is silently shadowed.

The fix is the habit you saw in the file tree above. Put the blueprint's templates in a subfolder named after the blueprint (blog/templates/blog/index.html) and render them with the prefix, render_template("blog/index.html"). The example used the same names in its in-memory template loader. A side benefit: the application can override any blueprint template by providing a file with the same path in its own templates folder.

Static files work through an automatically added endpoint called blueprint_name.static, which is why the template could call url_for('blog.static', filename='blog.css'). The route is static_url_path plus the filename; the example set it to /assets, giving /blog/assets/blog.css. Without static_url_path it would be the folder name, /blog/static/blog.css. The app's own static route still exists, as the listing showed. More on static assets in Static Files and Assets.

Error handlers

Blueprints can register error handlers in two ways, and the difference is a classic source of confusion:

  • @bp.errorhandler(404) handles errors only when the error was raised inside one of that blueprint's views, for example by abort(404).
  • @bp.app_errorhandler(403) registers a handler for the whole application, wherever the error occurs. It is a convenient way for a blueprint to ship the error pages the rest of the app should use.

There is a catch for 404. When a URL matches no route at all, Flask has not found any view, so it cannot know which blueprint "owns" the failure. Such unmatched-URL errors can only be handled by an app-level handler. The next example shows all the cases together.

Python Blueprint and app-level error handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the results line by line:

  • /api/items/9 calls abort(404) inside the api view, so the blueprint's JSON handler answers.
  • /shop/cart also aborts with 404, but shop has no handler of its own, so Flask falls back to the app's handler.
  • /shop/secret raises 403 in shop, yet the response comes from a handler registered by api with app_errorhandler, because that one is global.
  • /api/boom raises a ValueError, which no blueprint handles, so the app-level handler for ValueError runs.
  • /api/nope and /nowhere match no route, so even though /api/nope starts with the api prefix, the app's 404 handler answers. If your API should return JSON for unknown URLs too, add an app-level handler that checks request.path.startswith("/api/").

Error Handling and Custom Error Pages covers handlers in more depth.

Blueprint-level hooks

Blueprints can attach request hooks that run only for their own views: @bp.before_request, @bp.after_request, @bp.teardown_request and @bp.context_processor. The app_ variants (before_app_request and friends) apply to every request in the app. This makes a blueprint ideal for a section with its own rules, such as an admin area that must check a token first.

The next example also registers the same blueprint twice. register_blueprint(admin, name="staff", url_prefix="/staff") gives the second copy its own name, so its endpoints become staff.dashboard and url_for(".dashboard") stays correct inside each copy.

Python before_request on a blueprint, and registering twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The public home page is unaffected by the admin guard, and the guard blocks /admin/ with a 403 until the header is sent. Inside a request, request.blueprint tells you which blueprint is handling it and request.endpoint gives the full endpoint name, which is handy for logging and for highlighting the active item in a navigation menu.

Blueprints can also be nested: parent.register_blueprint(child) produces endpoints like parent.child.view and joins the URL prefixes. Use it sparingly; one level covers most apps.

Common mistakes

  • BuildError after moving a view into a blueprint. The endpoint changed from index to blog.index. Update every url_for call and template link.
  • Forgetting to register. A blueprint that is defined but never passed to register_blueprint produces 404s without any error.
  • Circular imports between the blueprint package and the factory. Create the blueprint object in its own module and import the blueprint inside create_app.
  • Template name clashes. Use blueprint_name/ subfolders for templates.
  • Expecting bp.errorhandler(404) to catch unknown URLs. It only sees errors from its own views; use an app-level handler for the rest.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A view function index is defined in a blueprint named blog. What is its endpoint?

    Endpoints of blueprint views are prefixed with the blueprint name and a dot, which keeps equally named views in different blueprints apart.
  2. 2. Inside a view of the blog blueprint, what does url_for('.show', post_id=3) refer to?

    A leading dot is a shortcut for the blueprint that handles the current request.
  3. 3. Two blueprints both contain a template file named index.html directly in their templates folders. What is the likely problem?

    Template folders share one namespace. Put each blueprint's templates in a subfolder named after the blueprint and render blog/index.html.
  4. 4. Which decorator registers an error handler that applies to the whole application, from inside a blueprint?

    app_errorhandler is the application-wide variant. Plain errorhandler on a blueprint is limited to errors raised by that blueprint's views.
  5. 5. A request for /api/nope matches no route. Which handler can produce the response?

    No view was matched, so Flask cannot attribute the error to a blueprint. Only app-level handlers see unmatched URLs.

Summary

  • A Blueprint groups routes, handlers, templates and static files; app.register_blueprint() mounts it, optionally with a url_prefix.
  • Endpoints become blueprint.function; use url_for(".function") for the current blueprint and the full name from elsewhere.
  • Keep blueprint templates in a subfolder named after the blueprint to avoid clashes; blueprint static files get a blueprint.static endpoint.
  • bp.errorhandler is local to the blueprint's views, bp.app_errorhandler is global, and unmatched URLs are only seen by app-level handlers.
  • bp.before_request and friends run only for that blueprint; before_app_request affects every request.
  • The same blueprint can be registered several times under different names and prefixes.

Next: Configuration and Environments, keeping settings and secrets out of your code.