我在尝试使用应用程序工厂模式时遇到问题。我有一个工作中的 Flask 应用程序,但代码结构很糟糕。今天我改进了结构,创建了一个更合适的应用程序工厂。
为了访问用户身份,我习惯了以下before_request
工作正常。
# user_module/authorization.py
@current_app.before_request
def before_request():
if hasattr(current_user, 'id'):
g.identity = Identity(current_user.id)
load_identity()
else:
g.identity = AnonymousIdentity
但是,我将基本应用程序移至
# application.py
def config_extensions(application):
mysql.init_app(application)
login_manager.init_app(application)
principal.init_app(application)
def config_blueprints(application):
from w_app.user_module.views import user_blueprint
application.register_blueprint(user_blueprint)
from w_app.admin_module.views import admin_blueprint
application.register_blueprint(admin_blueprint)
from w_app.main_module.views import main_blueprint
application.register_blueprint(main_blueprint)
# Define create_app function, the core of the Flask App
def create_app():
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.secret_key = 'cvwenjvibvuiu934vh843vn839f234nc893cu9234'
# with app.app_context():
# Add a debug toolbar to all responses in dev
app.config['SECRET_KEY'] = 'cvwenjvibvuiu934vh843vn839f234nc893cu9234'
DebugToolbarExtension(app)
config_extensions(app)
config_blueprints(app)
return app
现在授权告诉我它找不到应用程序上下文。
RuntimeError: Working outside the application context
我试图将它移动并尝试使用with app.app_context
但没有成功。