Dae*_*yth 5 python connection-pooling sqlalchemy psycopg2
我正在使用sqlalchemy的声明性映射系统添加一个新的ORM类。我的代码库有一个现有的psycopg2连接池,我想重用该连接池-我不希望使用orm类的代码拥有自己的池。有很多直接调用get_conn
psycopg2池的现有代码,因此我也不想只替换它。
我在构造要连接的引擎时遇到问题。
pool_config = {...}
POOL = psycopg2.pool.ThreadedConnectionPool(0, 32, **pool_config)
[...]
engine = sqlalchemy.create_engine('postgresql://', pool=POOL)
Session = sqlalchemy.orm.sessionmaker(bind=engine)
...
Run Code Online (Sandbox Code Playgroud)
问题是我打给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'
Run Code Online (Sandbox Code Playgroud)
是否可以通过这种方式使用现有的池,或者是否需要创建一个单独的连接池以供这些类使用?
您可以使用自定义连接功能:
create_engine('postgresql+psycopg2://', creator=POOL.getconn)
Run Code Online (Sandbox Code Playgroud)