psycopg2连接的线程安全连接管理器。
项目描述
此包包含对psycopg2的托管连接,它提供对底层psycopg2.connection对象的线程安全独占访问。
这允许许多线程共享同一个连接实例(避免与建立新的PostgreSQL连接相关的TCP和进程启动成本),并确保线程不会在事务进行中释放连接——无论是由于开发人员错误,还是在线程与数据库交互时未处理的异常。
ManagedConnection 还将确保在进入托管上下文时关闭的连接将被打开。
用法
创建托管连接
>>> from pgmanagedconnection import ManagedConnection
>>>
>>> dsn = 'postgres:///postgres' # a libpq connection string
>>> manager = ManagedConnection(dsn)
>>> manager
<ManagedConnection: postgres:///postgres (closed)>
执行查询
>>> with manager() as connection:
... cursor = connection.cursor()
... cursor.execute('SELECT 1')
... cursor.fetchone()
... connection.commit()
(1,)
处理未提交的事务
当退出上下文管理器时留下打开的事务将导致 RuntimeError。这也导致任何打开的事务被隐式回滚。
>>> with manager() as connection:
... cursor = connection.cursor()
... cursor.execute('SELECT 1')
Traceback (most recent call last):
...
RuntimeError: Did not commit or rollback open transaction before releasing connection.
处理错误
如果在遇到未处理的异常时,当前打开的事务将被回滚。
>>> import psycopg2
>>> with manager() as connection:
... cursor = connection.cursor()
... cursor.execute('SELECT 1')
... assert manager.status is psycopg2.extensions.TRANSACTION_STATUS_INTRANS
... raise NotImplementedError()
Traceback (most recent call last):
...
NotImplementedError
>>> manager.status is psycopg2.extensions.TRANSACTION_STATUS_IDLE
True
开发
测试
可以使用 make test 运行测试套件。
它假定有一个运行并可访问的PostgreSQL服务器。连接详情已推迟到底层的 libpq 实现中,可以使用 libpq环境变量 指定默认值。
也支持 tox 作为测试运行器(如果已安装。)
使用Docker进行测试
$ export PGPORT=5432
$ docker run -dp $PGPORT:5432 postgres
$ PGUSER=postgres make test
如果使用boot2docker,也需要设置环境变量PGHOST为虚拟机的IP地址。
$ PGUSER=postgres PGHOST=$(boot2docker ip) make test
项目详情
关闭
psycopg2-managed-connection-1.0.0.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 5159e4ffaf9bb102c5d7d0e2a7bfff8e7e422aa9a06c282558db5b456d6a1215 |
|
MD5 | 8874d826b1fe51981829e997ff7fa550 |
|
BLAKE2b-256 | 517e23a9b380daeda1ebc1fe127cc4d1fe49eba87aaae853e904f05ede820972 |