Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Dendi Handian
Dendi Handian

Posted on • Edited 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 modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

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'}]})
Enter fullscreen modeExit fullscreen mode

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'}]})
Enter fullscreen modeExit fullscreen mode

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)
Enter fullscreen modeExit fullscreen mode

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

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Data Engineer - Building Data Lake & Modern Data Architecture
  • Location
    Jakarta
  • Education
    B.S. Computer Science
  • Work
    Data Engineer at Media Production Company
  • Joined

More fromDendi Handian

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp