Extend a blueprint in Flask, splitting it into several files

Viewed 884

In flask, I have a blueprint that is getting a bit too long and I'd like to split it into several files, using the same route /games

I tried extending the class, but it doesn't work?

# games.py
from flask import Blueprint

bp = Blueprint('games', __name__, url_prefix='/games')

@bp.route('/')
def index():
    ...

.

# games_extend.py
from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"

Am I doing something wrong or is there a better way?

2 Answers

You can make it work using absolute path names (packages), here's how:

app.py

from __future__ import absolute_import
from flask import Flask
from werkzeug.utils import import_string

api_blueprints = [
    'games',
    'games_ext'
]

def create_app():
    """ Create flask application. """
    app = Flask(__name__)

    # Register blueprints
    for bp_name in api_blueprints:
        print('Registering bp: %s' % bp_name)
        bp = import_string('bp.%s:bp' % (bp_name))
        app.register_blueprint(bp)

    return app

if __name__ == '__main__':
    """ Main entrypoint. """
    app = create_app()
    print('Created app.')
    app.run()

bp/init.py

bp/games.py

from __future__ import absolute_import
from flask import Blueprint, jsonify

bp = Blueprint('games', __name__, url_prefix='/games')

@bp.route('/')
def index():
    return jsonify({'games': []})

bp/games_ext.py

from .games import bp

@bp.route('/test')
def test_view():
    return "Hi!"

Start your server using: python -m app

Then send Get queries to /games/ and /games/test/ endpoints. Worked for me.

Cheers !

In latest version of Flask, it supports Nested Blueprints

They can now be successfully divided into multiple files and imported into the parent one. Additionally, note the url_prefix parameter which can be used to divide files based on functionality but with same routes in different files.

Related