如何使用sqlalchemy connectionpool创建会话?

时间:2018-12-20 13:40:42

标签: python mysql session sqlalchemy connection-pooling

我无法同时使用引擎,连接池和会话。我想做的是创建一个应用程序范围的引擎和池。然后在需要时从connectionpool创建会话。下面是我的代码示例:

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()给出错误“错误:'函数'对象没有属性'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)

在上面的示例中,他们将会话与连接绑定在一起。我想知道在使用会话时是否有必要使用connectionpool。如果是,那么如何创建connectionpool并将会话与从池中获得的连接绑定。

1 个答案:

答案 0 :(得分:0)

您没有正确调用engine.connect()方法。如果像这样在其上加上括号:

...
mypool = pool.QueuePool(getConnection(), max_overflow, pool_size)
conn = mypool.connect()
session = Session(bind=conn)
...

它应该正常工作。