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
and the file is the simple flask app like this:
fromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhello():return'Hello World!'if__name__=='__main__':app.run(debug=True)
Creating Products and Stores Blueprints
For examples, let's create a folder namedblueprints
and also create theproducts_blueprints
andstores_blueprints
- project |_ blueprints |_ products_blueprint.py |_ stores_blueprint.py |_ app.py
and for the blueprints, let's make them simple like these:
blueprints/products_blueprints
:
fromflaskimportBlueprint,jsonifyproducts_blueprint=Blueprint('products_blueprint',__name__)@products_blueprint.route('/api/products')defproduct_list():returnjsonify({'data':[{'id':1,'name':'Cappucinno'}]})
blueprints/stores_blueprints
:
fromflaskimportBlueprint,jsonifystores_blueprint=Blueprint('stores_blueprint',__name__)@stores_blueprint.route('/api/stores')defstore_list():returnjsonify({'data':[{'id':1,'name':'4th Avenue Cafe'}]})
Importing and Registering the Blueprints to Flask App
Let's modify theapp.py
to import the blueprints and register them to the app:
fromflaskimportFlaskfromblueprints.products_blueprintimportproducts_blueprintfromblueprints.stores_blueprintimportstores_blueprintapp=Flask(__name__)@app.route('/')defhello():return'Hello World!'app.register_blueprint(products_blueprint)app.register_blueprint(stores_blueprint)if__name__=='__main__':app.run(debug=True)
That's it. Try to run and access theapi/products
andapi/stores
to make sure it works.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse