0

I'm building a small flask application and I want to have a modular structure in my project.

In Django I could just write two separate folders with their own urls.py, register them in my settings.py and create routes to them in base urls.py.

How to achieve this kind of modularity in flask? Preferably with as little code as possible.

Bonus points if all this can be easily done without extensions.

davidism
  • 121,510
  • 29
  • 395
  • 339
tornikeo
  • 915
  • 5
  • 20

1 Answers1

1

You are looking for blueprints.

app.py
blueprints/
    sample_blueprint.py
    another_blueprint.py

Blueprints are like apps but not apps. (very lame explanation but let me show you some code)

# sample_blueprint.py
from flask import Blueprint

# just like `app = Flask(__name__)`
SAMPLE_BLUEPRINT = Blueprint('sample_blueprint', __name__)

# just like `@app.route('/sample')`
@SAMPLE_BLUEPRINT.route('/sample')
def sample():
    return 'Sample'

And then in app.py you have to register it.

# app.py
from flask import Flask

from blueprints.sample import SAMPLE_BLUEPRINT


app = Flask(__name__)

# Register all the blueprints, url_prefix is optional
app.register_blueprint(SAMPLE_BLUEPRINT, url_prefix='/sample-br')


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

You can now run the app (python3 app.py) and goto localhost:5000/sample-br/sample and see the response of the blueprint route.

This code is not tested. It is just to give you a starting idea. Please read the docs and try it out on your own and find out how blueprints fit into a Flask project.

Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36