Organizing your routes into different files can greatly improve the structure and maintainability of your Flask application, especially as it grows larger. Flask allows you to define routes in separate Python modules and then import those modules into your main Flask application.
Here’s a basic example of how you can do this:
- Create a folder named
routes(or any name you prefer) in your Flask application directory. - Inside the
routesfolder, create Python modules for different sets of routes. For example, you might haveuser_routes.py,admin_routes.py,api_routes.py, etc. - Define your routes in each of these modules using Flask’s
@app.routedecorator. - Import these route modules in your main Flask application file.
Here’s a simplified directory structure:
your_flask_app/
app.py
routes/
__init__.py
user_routes.py
admin_routes.py
api_routes.pyuser_routes.py might look like this:
from flask import Blueprint
user_bp = Blueprint('user', __name__)
@user_bp.route('/profile')
def profile():
return 'User Profile Page'
@user_bp.route('/settings')
def settings():
return 'User Settings Page'admin_routes.py might look like this:
from flask import Blueprint
admin_bp = Blueprint('admin', __name__)
@admin_bp.route('/dashboard')
def dashboard():
return 'Admin Dashboard Page'
@admin_bp.route('/users')
def manage_users():
return 'Manage Users Page'In your app.py file, you would then import and register these blueprints:
from flask import Flask
from routes.user_routes import user_bp
from routes.admin_routes import admin_bp
app = Flask(__name__)
app.register_blueprint(user_bp, url_prefix='/user')
app.register_blueprint(admin_bp, url_prefix='/admin')
if __name__ == "__main__":
app.run(debug=True)Now you can access you admin page using url : https://localhost:5000/admin/dashboard
and you can access you user page using url : https://localhost:5000/user/profile
This way, your routes are organized into separate files, making it easier to manage and maintain your Flask application.
