【发布时间】:2018-12-22 02:45:16
【问题描述】:
我在同时使用引擎、连接池和会话时遇到问题。我想做的是创建一个应用程序范围的引擎和池。然后随时从连接池创建会话。以下是我的代码示例:
import sqlalchemy.pool as pool
engine = createEngine(pool_size, pool.QueuePool)
Session = sessionmaker()
def getConnection():
try:
return engine.connect()
except:
return False
mypool = pool.QueuePool(getConnection(), max_overflow, pool_size)
conn = mypool.connect()
session = Session(bind=conn)
result = session.query(Models.Features).all()
在上面的代码中 session.query() 给出错误“error:'function' object has no attribute 'contextual_connect.
我使用了页面https://docs.sqlalchemy.org/en/latest/orm/session_basics.html 中标题为“使用备用参数创建临时会话对象”下的段落作为参考。这是我使用的上述页面的代码示例:
# at the module level, the global sessionmaker,
# bound to a specific Engine
Session = sessionmaker(bind=engine)
# later, some unit of code wants to create a
# Session that is bound to a specific Connection
conn = engine.connect()
session = Session(bind=conn)
在上面的示例中,他们将会话与连接绑定。我想知道在使用会话时是否需要使用连接池。如果是,那么如何创建连接池并与从池中获得的连接绑定会话。
【问题讨论】:
-
一个诚实的问题:为什么要为仅使用
engine本身就可以实现的目标而烦恼?在您的示例代码中,您似乎基本上是在engine持有的池顶部添加了一个冗余QueuePool。此外,这似乎是一个“错字”问题,因为答案是“添加括号”。 -
@IljaEverilä 我已经尝试使用“mypool.connect()”,但效果不佳。正如您所提到的,我可以仅使用引擎来进行池化,您能解释一下吗?我的理解是,创建一个启用池的引擎并与引擎绑定会话,但不是连接。那是对的吗?所以后面会使用池中的连接。我会试试这个并更新。谢谢。
-
问题是你调用了一个你不应该调用的函数,即
pool.QueuePool(getConnection(), ...),并且没有调用它应该调用的函数:conn = mypool.connect。
标签: python mysql session sqlalchemy connection-pooling