使用现有的psycopg2连接池创建sqlalchemy引擎 [英] Create a sqlalchemy engine using an existing psycopg2 connection pool

查看:190
本文介绍了使用现有的psycopg2连接池创建sqlalchemy引擎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm adding a new ORM class using sqlalchemy's declarative mapping system. My codebase has an existing psycopg2 connection pool, which I want to reuse - I don't want code using my orm classes to have its own pool. There's a lot of existing code which directly calls get_conn on the psycopg2 pool, so I don't want to just replace it either.

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

I'm having a problem constructing the engine to connect with.

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'

是可能以这种方式使用我现有的池,还是需要为这些类使用一个单独的连接池?

Is it possible to use my existing pool in this way, or do I need to make a separate connection pool to be used by these classes?

推荐答案

您可以使用自定义连接函数

create_engine('postgresql+psycopg2://', creator=POOL.getconn)

这篇关于使用现有的psycopg2连接池创建sqlalchemy引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆