我在尝试使事情与应用程序工厂模式一起工作时遇到问题。我有一个工作正常的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
而不成功。