我有一个按需创建数据库连接的应用程序。但是我想要一个功能,如果创建连接花费的时间超过一定时间,则应该超时。所以我使用多进程来生成一个进程, 并在一定时间后加入,并检查进程状态。此过程运行良好,但我无法从中检索连接对象 生成的进程,因为它不可序列化。有帮助吗?
import psycopg2
import multiprocessing
from multiprocessing import Process
config = {
"user": "xxx",
"password": "xxx",
"host": "xxx",
"database": "xxx",
}
def create_postgres_connection(config, return_dict):
# Connect to the database, we have to timeout this function if it takes too long.
host = config['host']
database = config['database']
username = config['user']
password = config['password']
connection = psycopg2.connect(host=host, database=database, user=username, password=password)
return_dict['connection'] = connection
def run_with_limited_time(func, args, kwargs, time):
"""Runs a function with time limit
:param func: The function to run
:param args: The functions args, given as tuple
:param kwargs: The functions keywords, given as dict
:param time: The time limit in seconds
:return: True if the function ended successfully. False if it was terminated.
"""
p = Process(target=func, args=args, kwargs=kwargs)
p.start()
p.join(5)
if p.is_alive():
p.terminate()
print('Timed Out')
return False
return True
if __name__ == '__main__':
manager = multiprocessing.Manager()
return_dict = manager.dict()
run_with_limited_time(create_postgres_connection, (config, return_dict), {}, 3)
print(return_dict)
答案 0 :(得分:1)
您将无法使用多重处理来执行此操作,因为它依赖于酸洗对象才能在进程之间转移。而且,您发现,连接对象无法腌制。
但是,我认为您还是不需要这样做,因为Postgres在连接时允许使用connect_timeout
参数,这实际上是您需要解决的问题。 connect_timeout
以秒为单位指定。 [postgres docs]
根据psycopg2 docs,您可以将任何数据库特定的参数作为关键字参数传递。
它看起来像:
def create_postgres_connection(config, connection):
# Connect to the database
host = config['host']
database = config['database']
username = config['user']
password = config['password']
connection = psycopg2.connect(host=host, database=database, user=username,
password=password, connect_timeout=3)
return connection