Python psycopg2在执行后出现错误

2024-10-02 20:30:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中执行代码时遇到此错误

这是我的Python-DataBaseHelper.py:

import psycopg2
#class
class DataBaseHelper:
    database = "testdata";user = "test";password = "pass123"; host = "mtest.75tyey.us-east-1.rds.amazonaws.com"

    #create and return the connection of database
    def getConection(self):
        self.conn = psycopg2.connect(database=self.database, user = self.user, password = self.password, host = self.host, port = "5432")
        return self.conn

然后导入此文件并在另一个python文件-MyScript.py中使用:

import sys
import uuid
from DBHelper import DataBaseHelper
from ExecutionLogHelper import ExecutionLogHelper
from GotUtility import GotUtility


class MyScript:
   def __init__(self,):
        self.con = DataBaseHelper().getConection()
        self.logHelper = ExecutionLogHelper()
        self.uuid = self.logHelper.Get_TEST_Run_Id()

当我同时运行代码时,会出现以下错误:

psycopg2.errors.AdminShutdown: terminating connection due to administrator command
SSL connection has been closed unexpectedly

我不明白为什么我会犯这个错误。当我再次运行Python程序时,它工作正常。我检查了Postgres服务器是否正在运行,没有重新启动,没有关闭的信号。这对我来说每隔几个小时就会发生一次


Tags: 代码frompyimportselfhostreturn错误
2条回答

之所以发生这种情况,是因为psycopg2试图通过SSL连接到AWS Postgresql,但失败了

  1. 尝试使用sslmode=disable连接
    def getConection(self):
        self.conn = psycopg2.connect(database=self.database,
                                     user = self.user,
                                     password = self.password,
                                     host = self.host,
                                     port = "5432",
                                     sslmode="disable")
        return self.conn
    
    
    
    
  2. 如果AWS Postgresql配置为强制ssl连接,即参数rds.force_ssl=1,则方法1将不起作用。如果启用setrds.force_ssl,则拒绝所有非SSL连接。在这种情况下,请尝试使用以下方式进行连接:

$ psql -h testpg.cdhmuqifdpib.us-east-1.rds.amazonaws.com -p 5432 "dbname=testpg user=testuser sslrootcert=rds-ca-2015-root.pem sslmode=verify-full"

有关如何使用各种驱动程序通过ssl连接到AWS RDS的详细信息:AWS RDS SSL

经过一番挖掘,我找到了一些答案。根据this link

This error message comes from intervention by a program external to Postgres: http://www.postgresql.org/message-id/4564.1284559661@sss.pgh.pa.us

为了详细说明,this link说:

If user stop postgresql server with "service postgresql stop" or if any SIGINT has been called on the postgresql PID then this error will occur.

解决方案: 由于代码是并行运行的,因此在同一行同时执行多个事务可能会导致此错误。所以你必须确保这不会发生Look here for more details

When you update rows in a transaction, these rows are locked until the transaction is committed.

如果您无法做到这一点,我建议您启用查询日志记录,并查看其中是否有奇怪之处

相关问题 更多 >