python - SQLAlchemy 对象会话属性错误:__enter__
问题描述
当我在 with 语句中使用 SQLAlchemy 会话时,它不起作用。它应该可以工作,因为根据源代码sessionmaker
返回一个对象和方法。我检查了一下,我正在使用最新版本(SQLAlchemy==1.3.22)。Session
__enter__
__exit__
用于查明错误的代码:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine(
'sqlite:////devdb/sqlite.db',
echo=True
)
Session = sessionmaker(bind=engine)
with Session() as session:
print('it worked!')
错误:
Traceback (most recent call last):
File "test.py", line 11, in <module>
with Session() as session:
AttributeError: __enter__
我也尝试了自己的课程,只是为了测试它,并且发生了同样的错误:
class MySessionMaker(sessionmaker):
def __init__(self, bind):
super().__init__(bind=bind)
def __enter__(self):
return self()
def __exit__(self, exception_type, exception_value, exception_traceback):
self.close()
Session = MySessionMaker(bind=engine)
我在网上找不到关于这个错误的任何信息,有没有其他人遇到过这个问题?
解决方案
推荐阅读
- oracle - dba_objects 表 Oracle 中的 last_ddl_time
- java - 如何解决尝试在空引用上调用虚拟方法 android.content.res.Resources
- java - 运行 PhotosLibraryClient.initialize() 时出现 IncompatableClassChange 错误
- angular - Socket.io 不会传播/发射字符串
- vue.js - 导航守卫不断循环
- sql-server - 为队列中的项目创建顺序日期范围
- java - 使用 Spring 的中央配置文件
- javascript - 如何使这个多点形式排列
- python - 如何在 wxmpl 中使用时间格式(不适用于 MATPLOTLIB)
- akka-stream - 如何检测 Akka Stream 中特定持续时间的间隙?