flask的orm模型(Flask 的 ORM 模型),操作过程过如下示例代码运行报错
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
user = 'root'
password = '123456'
database = 'school'
uri = 'mysql+pymysql://%s:%s@localhost:3306/%s' % (user, password, database)
app.config['SQLALCHEMY_DATABASE_URI'] = uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Student(db.Model):
__tablename__ = 'students'
sno = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(255))
age = db.Column(db.Integer)
students = Student.query.all()
for student in students:
print(student.sno, student.name, student.age)
错误如下:
C:\Users\DELL\AppData\Local\Programs\Python\Python39\python.exe D:\python\flask\ORM模型\db.py
Traceback (most recent call last):
File "D:\python\flask\ORM模型\db.py", line 23, in <module>
students = Student.query.all()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\model.py", line 31, in __get__
cls, session=cls.__fsa__.session() # type: ignore[arg-type]
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\orm\scoping.py", line 218, in __call__
sess = self.registry()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\sqlalchemy\util\_collections.py", line 639, in __call__
key = self.scopefunc()
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\flask_sqlalchemy\session.py", line 102, in _app_ctx_id
return id(app_ctx._get_current_object()) # type: ignore[attr-defined]
File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\werkzeug\local.py", line 513, in _get_current_object
raise RuntimeError(unbound_message) from None
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
进程已结束,退出代码1
于是针对代码透露的信息进行搜索:
Traceback (most recent call last):
#意思是:回溯(最近的一次呼叫)
#这里表示您的Python程序出现了异常,括号中通俗的解释就是代码中引发异常的位置。
RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.
#运行时错误:在应用程序上下文之外工作。这通常意味着您尝试使用需要当前应用程序的功能。
#要解决此问题,请使用 with app.app_context() 设置应用程序上下文。有关详细信息,请参阅文档。
解决方案:
在对应的报错代码前方添加一句with app.app_context():
参考文章: