【问题标题】:Python - psycopg2 giving error after executionPython - psycopg2 在执行后给出错误
【发布时间】:2020-04-17 09:13:33
【问题描述】:

在 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 服务器正在运行,没有重新启动,没有关闭信号。这对我来说每隔几个小时就会发生一次。

【问题讨论】:

  • 如何同时运行?
  • 我有一个 Ubuntu 服务器。我登录,创建多个屏幕,然后同时运行我的代码。
  • 我注意到您使用的是 AWS RDS 终端节点;您如何检查重启/关闭事件的信号?
  • @snakecharmerb 连接有时会打开超过 24 小时。
  • 你检查了这个答案吗? stackoverflow.com/a/57455876/1412564

标签: python psycopg2


【解决方案1】:

发生这种情况是因为 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 连接,即方法 1 将不起作用。参数rds.force_ssl = 1。如果启用设置rds.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

【讨论】:

    【解决方案2】:

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

    此错误消息来自外部程序的干预 Postgres:http://www.postgresql.org/message-id/4564.1284559661@sss.pgh.pa.us

    详细说明,this link 说:

    如果用户使用 "service postgresql stop" 停止 postgresql 服务器,或者如果在 postgresql PID 上调用了任何 SIGINT,则会发生此错误。

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

    当您更新事务中的行时,这些行会被锁定,直到事务提交为止。

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

    【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2013-04-19
    • 2018-07-05
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2023-03-18
    • 2012-09-02
    相关资源
    最近更新 更多