这是我发现设置烧瓶应用程序的最巧妙方法:
在 app.py 中:
from flask import Flask
from app.settings import DevConfig
from app.extensions import api, mysqldb, marsh, mongodb
def create_app(config=DevConfig):
"""Application factory. This is used to run the app from the root.
:param config: Object to configure app stored in settings.py
"""
app = Flask(__name__.split('.')[0])
app.config.from_object(config)
register_endpoints()
register_extensions(app)
return app
def register_extensions(app):
"""Registration of flask components."""
mysqldb.init_app(app)
marsh.init_app(app)
mongodb.init_app(app)
api.init_app(app)
然后在 extensions.py 我会有这样的东西:
from flask_restful import Api
from flask_httpauth import HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_pymongo import PyMongo
mysqldb = SQLAlchemy()
mongodb = PyMongo()
marsh = Marshmallow()
api = Api(prefix='/v1')
auth = HTTPBasicAuth()
这样我就有了分开的东西。可能有一种方法可以在扩展中循环 init_app ,但在我看来它会不那么干净。
要使用我然后从扩展文件中导入数据库。