如何解决如何修复“运行时错误:在应用程序上下文之外工作”什么时候用 Flask 创建蓝图?
我正在尝试创建蓝图并遇到了这个问题:
Traceback (most recent call last):
File "C:\Users\Max\PycharmProjects\python1\flask_first\__init__.py",line 3,in <module>
from models import db
File "C:\Users\Max\PycharmProjects\python1\flask_first\models.py",line 5,in <module>
current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html' # access to the SQL
File "C:\python3.9\lib\site-packages\werkzeug\local.py",line 347,in __getattr__
return getattr(self._get_current_object(),name)
File "C:\python3.9\lib\site-packages\werkzeug\local.py",line 306,in _get_current_object
return self.__local()
File "C:\python3.9\lib\site-packages\flask\globals.py",line 52,in _find_app
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this,set up an application context with app.app_context(). See the
documentation for more information.
我已经做了很多研究,但没有任何效果对我有用(或者我只是看起来不够好)。
这是 models.py
代码:
from flask_sqlalchemy import SQLAlchemy
from flask import current_app
current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html' # access to the SQL
current_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(current_app)
class users(db.Model):
__tablename__ = 'users'
_id = db.Column('id',db.Integer,primary_key=True)
name = db.Column(db.String(80))
email = db.Column(db.String(120))
password = db.Column(db.Integer)
def __init__(self,name,email,password):
self.name = name
self.email = email
self.password = password
这是__init__.py
:
from datetime import timedelta
from flask import Flask
from models import db
from flask_first.admin.second import second
def create_app():
app = Flask(__name__)
with app.app_context():
db.init_app(app)
return app
create_app.secret_key = 'hello world'
create_app.permanent_session_lifetime = timedelta(minutes=5) # setting the time for long-lasting session
if __name__ == '__main__':
db.create_all()
create_app.run(debug=True)
解决方法
在这里,我会将 my comment 扩展为答案。
Python 逐行执行您的代码,其中包括 import
语句。正如错误所示,当它进入 __init__.py
并到达 from models import db
行时,它立即跳转到 models.py
,并开始在那里执行您的行。 >
Traceback (most recent call last):
File "...\__init__.py",line 3,in <module>
from models import db
File "...\models.py",line 5,in <module>
current_app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.sqlite3.html'
此时,导入的 current_app
还不存在,因为 create_app
中的 __init__.py
似乎还没有被调用。在这里您会遇到常见的 Flask 错误“在应用程序上下文之外工作:
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this,set up an application context with app.app_context(). See the
documentation for more information.
大多数情况下您会遇到此类错误,解决方案是重新排列初始化代码。确保 Flask 应用实例已经在你做任何其他事情之前创建。它通常应该是您的代码所做的第一件事。
在 Quickstart tutorial from flask-sqlalchemy 之后,您可以将 db
对象初始化放在 app
初始化附近。
# Create app object
app = Flask(__name__)
# Set configs
app.config['...'] = ...
# Create db object
db = SQLAlchemy(app)
app
和 db
对象通常一起驻留在某个顶级主模块中。然后,在您需要单独设置每个组件的其他子模块(控制器、模型等)中,从主模块导入 app
和/或 db
:
from some_main_module import app,db
# Do stuff with app and db
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。