Robert Brax Robert Brax - 4 days ago 9
Python Question

How to organize one Blueprint with multiple routes files

I got Blueprint working properly.

App structure:

application.py

users/routes.py


In application.py I register the blueprint:

app.register_blueprint( users, url_prefix = '/users' )


And in users/routes.py I create it:

users = Blueprint( 'users', __name__, template_folder = "usersViews" )
@users.route( '/registration', methods = [ 'GET' ] )
def get_register_user_form( ):
# Code......


What I need to do is add other files into users/ from which I need to use @users.route like in:

users/route2.py

users/route3.py


But this won't work as the blueprint is only created in the original users/routes.py. I'm not sure the proper way to handle this case ? I guess recreating the blueprint in each route file with users = Blueprint( 'users', name, template_folder = "usersViews" ) is not the proper way to do so. So how could I achieve that ?

Answer

I would split some of this out into __init__.py files like this:

app structure:

__init__.py (main app)
users/__init__.py (for blueprint)
users/routes.py
users/routes2.py
users/routes3.py

then, in the main __init__.py setup your blueprints:

app = Flask(__name__)

from .users import users as user_blueprint
app.register_blueprint(user_blueprint, url_prefix='/users')

return app

now, in your users/__init__.py something like this:

from flask import Blueprint, url_for

users = Blueprint('users', __name__)

from . import routes, routes2, routes3

Then in users/routes.py, users/routes2.py, etc:

from . import users

Caveat: I've never actually done this! But this is the pattern I use for Flask blueprints and it seemed like it would solve your problem.

Comments