los*_*ost 6 python postgresql psycopg2 multiprocessing
我正在尝试将 psycopg2 的连接池与 python 的多进程库一起使用。
目前,尝试以上述方式在线程之间共享连接池会导致:
psycopg2.OperationalError: SSL error: decryption failed or bad record mac
Run Code Online (Sandbox Code Playgroud)
下面的代码应该重现错误,警告读者必须设置一个简单的 postgres 数据库。
psycopg2.OperationalError: SSL error: decryption failed or bad record mac
Run Code Online (Sandbox Code Playgroud)
我已经尝试过的:
withsql 查询中的语句隐式调用它。这会引发一个错误,声称连接对象不可pickle。注意:如果我sleep在除一个进程之外的所有进程中进行操作,非休眠进程运行良好并执行其查询,直到其余线程不休眠,然后我收到上述错误。
我已经读过的:
最后:
如何将连接池 (psycopg2) 与 python 的多进程(多处理)一起使用。我愿意使用其他库,只要它们与 python 和 postgresql 数据库一起工作。
这是我的解决方案。解决方案可以分为两部分:
test_query)更详细地参考问题中的示例:
创建将在每个进程中重复使用一个连接池的包装函数:
def multi_query(list_of_cols):
# create a new connection pool per Process
new_pool = new_connection_pool()
# Pass the pool to each query
for col in list_of_cols:
test_query(col, new_pool)
Run Code Online (Sandbox Code Playgroud)
修改查询函数以接受连接池:
老的test_query:
def test_query(col_attribute):
"""
Simple SQL query
"""
query = f"""SELECT *
FROM col
WHERE col = {col_attribute}
;"""
with ConnectionFromPool() as cursor:
cursor.execute(query)
result = cursor.fetchall()
return result
Run Code Online (Sandbox Code Playgroud)
新的test_query:
def test_query(col_attribute, connection_pool=None):
"""
Simple SQL query
"""
query = f"""SELECT *
FROM col
WHERE col = {col_attribute}
;"""
with ConnectionFromPool(connection_pool) as cursor:
cursor.execute(query)
result = cursor.fetchall()
return result
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1394 次 |
| 最近记录: |