简体   繁体   English

Asnycpg PostgreSQL 连接问题

[英]Asnycpg PostgreSQL connection issues

I'm using Python with asnycpg to interact with my PostgreSQL database.我正在使用 Python 和asnycpg来与我的 PostgreSQL 数据库进行交互。 After some time, if I don't interact with it and then try to do so, I get an connection is closed error.一段时间后,如果我不与它交互然后尝试这样做,我会收到一个连接已关闭的错误。 Is this a server side config or client side config issue?这是服务器端配置还是客户端配置问题? How to solve it?如何解决?

The database automatically closes the connection due to security reasons.由于安全原因,数据库会自动关闭连接。

So I suggest you to open the connection to db just before running queries with asyncpg, and then to reclose the connection right afterwards.因此,我建议您在使用 asyncpg 运行查询之前打开与 db 的连接,然后立即重新关闭连接。

Furthermore, you can manage the possible errors that you get when the connection is closed by properly rising exceptions.此外,您可以管理连接关闭时可能出现的错误,方法是适当地引发异常。

Take a look at this example:看看这个例子:

Import asyncpg
print("I'm going to run a query with asyncpg")

# if the connection to db is not opened, then open it
if not connection:
    # try to open the connection to db
    try:
        connection = await asyncpg.connect(
                host=YOUR_DATABASE_HOST,
                user=YOUR_DATABASE_USER,
                password=YOUR_DATABASE_PASS,
                database=YOUR_DATABASE_DB_NAME
            )
            except (Exception, asyncpg.ConnectionFailureError) as error:
                Print("Error while connecting to db: {}".format(error))
else:
    #connection already up and running
    pass

QUERY_STRING = """
    INSERT INTO my_table(field_1, field_2)
    VALUES ($1, $2);
"""

try:
    await connection.execute(QUERY_STRING, value_to_assign_to_field_1, value_to_assign_to_field_2)
    return None
# except (Exception, asyncpg.UniqueViolationError) as integrError:
    # print("You are violating unique constraint.")
except (Exception, asyncpg.ConnectionFailureError) as error:
    print("Connection to db has failed. Cannot add data.")
    return "{}".format(error)
finally:
    if (connection):
        await Utils.close_connection(connection)
    print("data has been added. closing the connection.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM