Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding routes when using an app factory

Tags:

python

flask

How are routes suppose to be handled in flask when using an app factory? Given a package blog that contains everything needed for the app and a management script that creates the app then how are you suppose to reference the app in the routes?

├── blog
    ├── manage.py 
    └── blog
        ├── __init__.py
        ├── config.py  
        └── routes.py

manage.py

#!/usr/bin/env python

from flask.ext.script import Manager

manager = Manager(create_app)

# <manager commands>
# ...
# ...

manager.add_option('-c', '--config', dest='config', required=False)
manager.run()

blog/__init__.py

from flask import flask
from .config import Default

def create_app(config=None):

    app = Flask(__name__)
    app.config.from_object(Default)

    if config is not None:
        app.config.from_pyfile(config)

    return app

blog/routes.py

@app.route()  # <-- erm, this won't work now!? 
def index():
     return "Hello"

The problem is the app is created outside the package so how are the routes suppose to be handled with a setup like this?

like image 640
Chris Seymour Avatar asked Nov 01 '15 21:11

Chris Seymour


1 Answers

Usually I use application factories with blueprint.

blog/__init__.py

from flask import flask
from .config import Default

def create_app(config=None):

    app = Flask(__name__)
    if config is not None:
        app.config.from_pyfile(config)
    else:
        app.config.from_object(Default)

    from blog.routes import route_blueprint
    app.register_blueprint(route_blueprint)

    return app

blog/routes.py

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

@route_blueprint.route()
def index():
     return "Hello"

docs: Application Factories

like image 127
lord63. j Avatar answered Sep 19 '22 19:09

lord63. j