我想构建我的Flask应用,例如:
./site.py ./apps/members/__init__.py ./apps/members/models.py
apps.members 是flask蓝图。
apps.members
现在,为了创建模型类,我需要拥有该应用程序,例如:
# apps.members.models from flask import current_app from flaskext.sqlalchemy import SQLAlchemy db = SQLAlchemy(current_app) class Member(db.Model): # fields here pass
但是,如果我尝试将该模型导入到我的Blueprint应用程序中,则会感到恐惧RuntimeError: working outside of request context。我如何在这里正确持有我的应用程序?相对导入可能有效,但是它们很丑陋,并且具有自己的上下文问题,例如:
Blueprint
RuntimeError: working outside of request context
from ...site import app # ValueError: Attempted relative import beyond toplevel package
该flask_sqlalchemy模块没有要与应用程序马上初始化-你可以这样做,而不是:
flask_sqlalchemy
# apps.members.models from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Member(db.Model): # fields here pass
然后在应用程序设置中,你可以调用init_app:
# apps.application.py from flask import Flask from apps.members.models import db app = Flask(__name__) # later on db.init_app(app)
这样可以避免周期性导入。
这种模式并没有必要在你把你所有的车型在一个文件中。只需将db变量导入每个模型模块即可。
例
# apps.shared.models from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
# apps.members.models from apps.shared.models import db class Member(db.Model): # TODO: Implement this. pass
# apps.reporting.members from flask import render_template from apps.members.models import Member def report_on_members(): # TODO: Actually use arguments members = Member.filter(1==1).all() return render_template("report.html", members=members)
# apps.reporting.routes from flask import Blueprint from apps.reporting.members import report_on_members reporting = Blueprint("reporting", __name__) reporting.route("/member-report", methods=["GET","POST"])(report_on_members)
# apps.application from flask import Flask from apps.shared import db from apps.reporting.routes import reporting app = Flask(__name__) db.init_app(app) app.register_blueprint(reporting)
注意:这是一些功能的草图 -显然,你可以做很多事来简化开发工作(使用create_app模式,在某些文件夹中自动注册蓝图等)。