使用现有的psycopg2连接池创建sqlalchemy引擎

时间:2016-01-29 16:13:06

标签: python sqlalchemy connection-pooling psycopg2

我正在使用sqlalchemy的声明性映射系统添加一个新的ORM类。我的代码库有一个现有的psycopg2连接池,我想重用它 - 我不希望使用我的orm类的代码拥有自己的池。有很多现有的代码直接在psycopg2池上调用get_conn,所以我不想只替换它。

我在构建要连接的引擎时遇到问题。

pool_config = {...}
POOL = psycopg2.pool.ThreadedConnectionPool(0, 32, **pool_config)

[...]

engine = sqlalchemy.create_engine('postgresql://', pool=POOL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
...

问题在于我打电话给create_engine;

  File "/home/ubuntu/environment/local/lib/python2.7/site-packages/sqlalchemy/engine/__init__.py", line 362, in create_engine
    return strategy.create(*args, **kwargs)
  File "/home/ubuntu/environment/local/lib/python2.7/site-packages/sqlalchemy/engine/strategies.py", line 159, in create
    event.listen(pool, 'first_connect', on_connect)
  File "/home/ubuntu/environment/local/lib/python2.7/site-packages/sqlalchemy/event/api.py", line 63, in listen
    _event_key(target, identifier, fn).listen(*args, **kw)
  File "/home/ubuntu/environment/local/lib/python2.7/site-packages/sqlalchemy/event/registry.py", line 190, in listen
    dispatch_descriptor = getattr(target.dispatch, identifier)
AttributeError: 'ThreadedConnectionPool' object has no attribute 'dispatch'

是否可以以这种方式使用我现有的池,或者我是否需要创建一个单独的连接池供这些类使用?

1 个答案:

答案 0 :(得分:0)

您可以使用custom connection function

.navbar-header