You can use blueprint
to organize and register your routes.
Essentially, you can have a folder structure like this:
app/ <-- your entire application folder
auth/ <-- blueprint package for /auth route
__init__.py <-- blueprint creation
routes.py <-- authentication routes
profile/
__init__.py <-- blueprint package for /profile route
routes.py <-- profile routes
__init__.py <-- ceate_app and blueprint registration
Under your routes package, for example in auth
folder:
# app/auth/__init__.py
# this is initialize auth blueprint
from flask import Blueprint
bp = Blueprint('auth',__name__,)
from app.auth import routes
Then you can put all your authentication
routes in auth/routes.py
, but instead of using app.route
, you need to use bp.route
like this:
# app/auth/routes.py
# this is where you can put all your authentication routes
from app.auth import bp
# notice here the route '/login' is actually prefixed with 'auth'
# because in the following code I added "url_prefix='/auth' " in the create_app() factory.
# the full routes will be 'auth/login' on your website.
@bp.route('/login', methods=['GET','POST'])
def login():
....your login code...
Then in your __init__.py
you can do this:
# app/__init__.py
from app.auth import bp as auth_bp
from app.profile import bp as profile_bp
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
app.register_blueprint(auth_bp,url_prefix='/auth')
app.register_blueprint(profile_bp,url_prefix='/profile')
This way all routes to yourdomain.com/auth/...
will be in app/auth/routes.py
; all routes to yourdomain.com/profile/...
will be in your app/profile/routes.py
.
Check this wonderful tutorial about Flask for more details:
Flask mega tutorial by Miguel Grinberg
This specific part is about how you can better organize your application structure.