Flask Blueprints

When building a Flask application, soon, the need of sorting the code somehow arises.
Too many routes in the main file is not a solution in the mid term.
Instead, using Blueprints to modularize the application provides a great way to extend the application code.

Let’s use a simple application folder structure:

1
2
3
4
5
6
└── app
├── models
│ └── user.py
├── resources
│   └── user.py
└── main.py

where the several endpoints are placed into the resources folder.

The code for the resource user.py is quite simple:

resources/user.py
1
2
3
4
5
6
7
8
9
10
11
from flask import jsonify, Blueprint
from app.models.user import User

user = Blueprint('user', __name__)
u = User()

@user.route('/user', methods=['GET'], strict_slashes=False)
def index():
users = u.get_users()
return make_response(jsonify({'message': "ok", 'users': users}), 200)

The main Flask application remains as follows:

main.py
1
2
3
4
5
6
7
8
9
from flask import Flask
from app.resources.user import user

app = Flask(__name__)
app.register_blueprint(user)

if __name__ == '__main__':
app.run(debug=True, port=5000)