search by tags

for the user

adventures into the land of the command line

flask blueprints

If you have a flask project which it is becoming quite large and you want to move things about, into places that will make it easier to maintain, how do you go about it?

One way is by using flask’s blueprints. Take this simple example:

$ tree
.
├── app.wsgi
├── index.py
└── templates
    ├── index.html
    └── login.html

– app.wsgi –

import sys
sys.path.append('/path/to/app/dir/')
from index import app as application

– index.py –

from flask, import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login')
def login():
    return render_template('login.html')

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

Adding more and more routes to the index.py is doable and everything works. But at some point, maybe it just becomes too unwieldy. Do you want to work with one file with 10000 lines of code? What if you stop working on the project for 6 months and come back to it after forgetting how it works? Well say you would like to use flask blueprints to improve the organisation of the project, how can one do that?

We make these simple changes.

$ tree
.
├── app.wsgi
├── main.py
├── views
    ├── __init__.py
    ├── index.py
    └── login.py
└── templates
    ├── index.html
    └── login.html

– app.wsgi –

import sys
sys.path.append('/path/to/app/dir/')
from main import app as application

– main.py –

from flask import Flask, render_template

app = Flask(__name__)

from views import *
app.register_blueprint(views)

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

– views/__init__.py –

from flask import Blueprint
views = Blueprint('views', __name__)

from .index import *
from .login import *

– views/index.py –

from . import views
from flask import render_template

@views.route('/')
def index():
    return render_template('index.html')

– views/login.py –

from . import views
from flask import render_template

@views.route('/login')
def login():
    return render_template('login.html')

Et voila. Organisation :)