DEV Community

Dendi Handian
Dendi Handian

Posted on • Updated on

Modular Flask App with Blueprints

If your flask project started to grow larger and many features added, you should not write them in a single file. Flask has its own way to separate the features using the blueprints.

Basic Structure and Files

As the starter, we only have one file inside our project:

- project
  |_ app.py
Enter fullscreen mode Exit fullscreen mode

and the file is the simple flask app like this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

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

Enter fullscreen mode Exit fullscreen mode

Creating Products and Stores Blueprints

For examples, let's create a folder named blueprints and also create the products_blueprints and stores_blueprints

- project
  |_ blueprints
     |_ products_blueprint.py
     |_ stores_blueprint.py
  |_ app.py
Enter fullscreen mode Exit fullscreen mode

and for the blueprints, let's make them simple like these:

blueprints/products_blueprints:

from flask import Blueprint, jsonify

products_blueprint = Blueprint('products_blueprint', __name__)

@products_blueprint.route('/api/products')
def product_list():
    return jsonify({'data': [{'id': 1, 'name': 'Cappucinno'}]})
Enter fullscreen mode Exit fullscreen mode

blueprints/stores_blueprints:

from flask import Blueprint, jsonify

stores_blueprint = Blueprint('stores_blueprint', __name__)

@stores_blueprint.route('/api/stores')
def store_list():
    return jsonify({'data': [{'id': 1, 'name': '4th Avenue Cafe'}]})
Enter fullscreen mode Exit fullscreen mode

Importing and Registering the Blueprints to Flask App

Let's modify the app.py to import the blueprints and register them to the app:

from flask import Flask

from blueprints.products_blueprint import products_blueprint
from blueprints.stores_blueprint import stores_blueprint

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

app.register_blueprint(products_blueprint)
app.register_blueprint(stores_blueprint)

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

Enter fullscreen mode Exit fullscreen mode

That's it. Try to run and access the api/products and api/stores to make sure it works.

Top comments (0)