psycopg2连接的线程安全连接管理器。
psycopg2-managed-connection的Python项目详细描述
此包包含一个用于psycopg2的托管连接,该连接提供 对底层psycopg2.connection对象的线程安全独占访问。
这允许许多线程共享同一个连接实例(避免 与建立新PostgreSQL相关的TCP和进程启动成本 并确保线程不会释放与 事务仍在进行中-可能是由于开发人员错误,或者是未处理的 线程与数据库交互时发生异常。
ManagedConnection还将确保 将打开输入托管上下文。
用法
创建托管连接
>>>frompgmanagedconnectionimportManagedConnection>>>>>>dsn='postgres:///postgres'# a libpq connection string>>>manager=ManagedConnection(dsn)>>>manager<ManagedConnection:postgres:///postgres(closed)>
查询
>>>withmanager()asconnection:...cursor=connection.cursor()...cursor.execute('SELECT 1')...cursor.fetchone()...connection.commit()(1,)
处理未提交的事务
<> P>退出上下文管理器时打开事务将导致 RuntimeError。这也会导致任何未结交易隐式地 后退。>>>withmanager()asconnection:...cursor=connection.cursor()...cursor.execute('SELECT 1')Traceback(mostrecentcalllast):...RuntimeError:Didnotcommitorrollbackopentransactionbeforereleasingconnection.
处理错误
如果未处理的异常是 遇到。
>>>importpsycopg2>>>withmanager()asconnection:...cursor=connection.cursor()...cursor.execute('SELECT 1')...assertmanager.statusispsycopg2.extensions.TRANSACTION_STATUS_INTRANS...raiseNotImplementedError()Traceback(mostrecentcalllast):...NotImplementedError>>>manager.statusispsycopg2.extensions.TRANSACTION_STATUS_IDLETrue
开发
测试
测试套件可以使用make test运行。
它假设postgresql服务器正在运行且可访问。连接详细信息 延迟到底层的libpq实现,默认值可以 使用libpq environment variables指定。
tox也支持作为测试运行程序(如果已安装)。
Docker测试
$ exportPGPORT=5432 $ docker run -dp $PGPORT:5432 postgres $ PGUSER=postgres make test
如果使用boot2docker,则PGHOST环境变量还需要 设置为虚拟机IP地址。
$ PGUSER=postgres PGHOST=$(boot2docker ip) make test