使用应用工厂时,如何在烧瓶中处理路线?给定一个包blog
包含应用程序所需的一切以及创建应用程序的管理脚本,那么您如何在路由中引用该应用程序?
├── 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()
博客/ __初始化__。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
博客/ routes.py
@app.route() # <-- erm, this won't work now!?
def index():
return "Hello"
问题是app是在包外创建的,那么如何使用这样的设置来处理路由?
答案 0 :(得分:6)
通常我使用具有蓝图的应用工厂。
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 improt Blueprint
route_blueprint = Blueprint('route_blueprint', __name__)
@route_blueprint.route()
def index():
return "Hello"