How to centralise routing in Flask using a single file instead of decorators? How to centralise routing in Flask using a single file instead of decorators? flask flask

How to centralise routing in Flask using a single file instead of decorators?


As you know decorators work as functions:

@app.route('/')def home():    return 'home'

equivalent to:

def home():    return 'home'home = app.route('/')(home)

But Flask already has special method add_url_rule for this. It used in route decorator.

def home():    return 'home'app.add_url_rule('/', None, home, {})

So you can create special module where will import view functions and add routes with add_url_rule. Do not forget execute this code before usage (import).

add_url_rule is creating Rule instance and adding it to Flask.url_map, so you can also explicitly create Rule and put it to url_map. But I hope this not need for you.

Update

With Flask you also can use Lazily Loading Views, see details in documentation: http://flask.pocoo.org/docs/patterns/lazyloading/.