Python 中创建 PostgreSQL 数据库连接池
作者:Yanbin Blog 发布时间:2024-01-19 22:33:37
习惯于使用数据库之前都必须创建一个连接池,即使是单线程的应用,只要有多个方法中需用到数据库连接,建立一两个连接的也会考虑先池化他们。连接池的好处多多,
1) 如果反复创建连接相当耗时,
2) 对于单个连接一路用到底的应用,有连接池时避免了数据库连接对象传来传去,
3) 忘记关连接了,连接池幸许还能帮忙在一定时长后关掉,当然密集取连接的应用势将耗尽连接,
4) 一个应用打开连接的数量是可控的
接触到 Python
后,在使用 PostgreSQL
也自然而然的考虑创建连接池,使用时从池中取,用完后还回去,而不是每次需要连接时创建一个物理的。Python
连接 PostgreSQL
是主要有两个包, py-postgresql
和 psycopg2
, 而本文的实例将使用后者。
Psycopg
在 psycopg2.pool
模块中提供了两个连接池的实现在,它们都继承自 psycopg2.pool.AbstractConnectionPool,
该抽象类的基本方法是
getconn(key=None):
获取连接putconn(conn, key=None, close=False):
归还连接closeall():
关闭连接池中的所有连接
两个连接池的实现类是
psycopg2.pool.SimpleConnectionPool(minconn, maxconn, *args, **kwars)
: 给单线程应用用的psycopg2.pool.ThreadedConnectionPool(minconn, maxconn, *args, **kwars)
: 多线程时更安全,其实就是在getconn()
和putconn()
时加了锁来控制
所以最安全保险的做法还是使用 ThreadedConnectionPool
, 在单线程应用中, SimpleConnectionPool
也不见得比 ThreadedConnectionPool
效率高多少。
下面来看一个具体的连接池实现,其中用到了 Context Manager
, 使用时结合 with
键字更方便,用完后不用显式的调用 putconn()
归还连接
db_helper.py
from psycopg2 import pool
from psycopg2.extras import RealDictCursor
from contextlib import contextmanager
import atexit
class DBHelper:
def __init__(self):
self._connection_pool = None
def initialize_connection_pool(self):
db_dsn = 'postgresql://admin:password@localhost/testdb?connect_timeout=5'
self._connection_pool = pool.ThreadedConnectionPool(1, 3,db_dsn)
@contextmanager
def get_resource(self, autocommit=True):
if self._connection_pool is None:
self.initialize_connection_pool()
conn = self._connection_pool.getconn()
conn.autocommit = autocommit
cursor = conn.cursor(cursor_factory=RealDictCursor)
try:
yield cursor, conn
finally:
cursor.close()
self._connection_pool.putconn(conn)
def shutdown_connection_pool(self):
if self._connection_pool is not None:
self._connection_pool.closeall()
db_helper = DBHelper()
@atexit.register
def shutdown_connection_pool():
db_helper.shutdown_connection_pool()
from psycopg2 import pool
from psycopg2 . extras import RealDictCursor
from contextlib import contextmanager
import atexit
class DBHelper :
def __init__ ( self ) :
self . _connection_pool = None
def initialize_connection_pool ( self ) :
db_dsn = 'postgresql://admin:password@localhost/testdb?connect_timeout=5'
self . _connection_pool = pool . ThreadedConnectionPool ( 1 , 3 , db_dsn )
@ contextmanager
def get_resource ( self , autocommit = True ) :
if self . _connection_pool is None :
self . initialize_connection_pool ( )
conn = self . _connection_pool . getconn ( )
conn . autocommit = autocommit
cursor = conn . cursor ( cursor_factory = RealDictCursor )
try :
yield cursor , conn
finally :
cursor . close ( )
self . _connection_pool . putconn ( conn )
def shutdown_connection_pool ( self ) :
if self . _connection_pool is not None :
self . _connection_pool . closeall ( )
db_helper = DBHelper ( )
@ atexit . register
def shutdown_connection_pool ( ) :
db_helper . shutdown_connection_pool ( )
几点说明:
只在第一次调用
get_resource()
时创建连接池,而不是在from db_helper import db_helper
引用时就创建连接池Context Manager
返回了两个对象,cursor
和connection
, 需要用connection
管理事物时用它默认时
cursor
返回的记录是字典,而非数组默认时连接为自动提交
最后的
@atexit.register
那个ShutdownHook
可能有点多余,在进程退出时连接也被关闭,TIME_WAIT
时间应该会稍长些
使用方式:
如果不用事物
from db_helper import db_helper
with db_helper.get_resource() as (cursor, _):
cursor.execute('select * from users')
for record in cursor.fetchall():
... process record, record['name'] ...
from db_helper import db_helper
with db_helper . get_resource ( ) as ( cursor , _ ) :
cursor . execute ( 'select * from users' )
for record in cursor . fetchall ( ) :
. . . process record , record [ 'name' ] . . .
如果需要用到事物
with db_helper.get_resource(autocommit=False) as (cursor, _):
try:
cursor.execute('update users set name = %s where id = %s', ('new_name', 1))
cursor.execute('delete from orders where user_id = %s', (1,))
conn.commit()
except:
conn.rollback()
with db_helper . get_resource ( autocommit = False ) as ( cursor , _ ) :
try :
cursor . execute ( 'update users set name = %s where id = %s' , ( 'new_name' , 1 ) )
cursor . execute ( 'delete from orders where user_id = %s' , ( 1 , ) )
conn . commit ( )
except :
conn . rollback ( )
在写作本文时,查看 psycopg 的官网时,发现 Psycopg 3.0
正式版在 2021-10-13 日发布了( Psycopg 3.0 released ), 更好的支持 async。在 Psycopg2 2.2 版本时就开始支持异步了。而且还注意到 Psycopg
的主要部分是用 C 实现的,才使得它效率比较高,也难怪经常用 pip install psycopg2
安装不成功,而要用 pip install psycopg2-binary
来安装的原因。
在创建连接池时加上参数 keepalivesXxx
能让服务器及时断掉死链接,否则在 Linux
下默认要 2 个小时后才断开。死链接的情况发生在客户端异常退出(如断电)时先前建立的链接就变为死链接了。
pool.ThreadedConnectionPool(1, 3, db_dsn, keepalives=1, keepalives_idle=30, keepalives_interval=10, keepalives_count=5)
PostgreSQL
服务端会对连接在空闲 tcp_keepalives_idle
秒后,主动发送tcp_keepalives_count 个 tcp_keeplive
侦测包,每个侦探包在 tcp_keepalives_interval
秒内都没有回应,就认为是死连接,于是切断它。
来源:https://www.tuicool.com/articles/Zzmeqyi


猜你喜欢
- 英文文档:len(s)Return the length (the number of items) of an object. The a
- 长话短说,今天介绍实现此功能的一个方法,需要了解的朋友可以参考下:一、JS 重载页面,本地刷新,返回上一页 代码如下:<a href=
- 写在前面:前一段时间 kejun 给我们培训JavaScript的时候,在幻灯片上推荐了很多特别经典的文章,其中就有这一篇。读过之后感觉很不
- 使用云服务器时,我们有时会连接数据库,但在使用Navicat Premium15来连接时,总会遇到报错。常规连接方式,以腾讯云服务器中的My
- 最近要搭建一个阿里云的LMAP环境,选了CentOS7来做搭建。1.ApacheCentos7默认已经安装httpd服务,只是没有启动。如果
- Python生产者消费者模型一、消费模式生产者消费者模式 是Controlnet网络 * 有的一种传输数据的模式。用于两个CPU之间传输数据,
- 在家里windows环境下搞了一次见 python MySQLdb在windows环境下的快速安装、问题解决方式ht
- 按照下面一步一步来,安 * p就是这么简单。脚本之家下载渗透测试软件Burp Suite Professionalhttps://www.jb
- 1.python函数运行原理import inspectframe = Nonedef foo(): bar()def bar(
- 在Python中可以使用paramiko模块中的sftp登陆远程主机,实现上传和下载功能。1.功能实现根据输入参数判断是文件还是目录,进行上
- # 从X和Y中取出相应步长对应的数组并保存至x_data和y_data中x_data = []y_data = []for i in ran
- 1.概述"""基础知识:1.多任务:操作系统可以同时运行多个任务;2.单核CPU执行多任务:操作系统轮流让各个
- 本文实例讲述了C#连接Oracle数据库的方法。分享给大家供大家参考。具体实现方法如下://1、添加引用 System.data.oracl
- 一、功能介绍1.MySQL Servers该功能是mysql主要的服务,也是必须安装的功能。2.Mysql WorkBench这个是mysq
- js运行效果,含公历农历,生肖及节日的javascript日历代码:<html><head><meta htt
- 将无权点文件转化成邻接矩阵目前点文件是两列Excel代码,在进行复杂网络运算时需要转化成邻接矩阵。我在网上找了一个代码,稍微修改了下,亲测可
- 我们以一个例子展开这个题目问题:python类对象A,先实例化一个A对象的实例b,接着给A对象添加一个类共享变量xxx,再实例化一个c,请问
- 代码如下import numpy as npfrom matplotlib import pyplot as plt# 用numpy生成数据
- 一、待搜索图二、测试集三、new_similarity_compare.py# -*- encoding=utf-8 -*-from ima
- 通过python对多个txt文件进行处理读取路径,读取文件获取文件名,路径名对响应的文件夹名字进行排序对txt文件内部的数据相应的某一列/某