4

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 ?

Robert Brax
  • 6,508
  • 12
  • 40
  • 69

1 Answers1

15

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.

abigperson
  • 5,252
  • 3
  • 22
  • 25
  • Genius, this is working, the secret was in the init files !! – Robert Brax Nov 30 '16 at 16:12
  • Great, glad I could help! – abigperson Nov 30 '16 at 16:14
  • 1
    Thanks! Why does from . import routes, routes2, routes3 needs to be after users = .... in users/__init__.py ? – Robert Brax Nov 30 '16 at 16:23
  • 1
    This is to avoid circular dependencies because the "routes" files also need to import the users Blueprint. It is essentially an "order of operations" thing with regards to how the code is read, some good discussion on it here: http://stackoverflow.com/questions/22187279/python-circular-importing – abigperson Nov 30 '16 at 16:58
  • 1
    found it really helpful. the order of imports was the key – Hammad Dec 10 '21 at 10:40