Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - psycopg2 giving error after execution

I am getting this error when executing my code in Python.

Here is my 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

Then I am importing this file and using in another python file - 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()

When I run my code concurrently, it gives me this error:

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

I am not able to understand why am I getting this error. When I run the Python program again, it works. And I checked the Postgres server is in running, no restart, no signal to shutdown. This keeps on happening every few hours for me.

like image 953
dang Avatar asked Apr 17 '20 09:04

dang


1 Answers

This is happening because psycopg2 is try to connect to AWS Postgresql over SSL and failing to do so.

  1. Try connecting with 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. Method 1 will not work if your AWS Postgresql is configured to force a ssl connection ie. parameter rds.force_ssl = 1. If you enable set rds.force_ssl all non-SSL connections are refused. In that case try connecting using something like this:

$ 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"

For more on how to connect to AWS RDS over ssl using various drivers : AWS RDS SSL.

like image 100
Rajat Singh Avatar answered Sep 30 '22 07:09

Rajat Singh