Home > database >  How to Connect Python to Heroku Postgres Database? #Error no encryption
How to Connect Python to Heroku Postgres Database? #Error no encryption

Time:03-28

I'm trying to stablish connection to Heroku Postgres Database and a receive this error:

psycopg2.OperationalError:
FATAL:  password authentication failed for user "hdyarfoicbluoo"
FATAL:  no pg_hba.conf entry for host "95.92.208.27", user "hdyarfoicbluoo", database "d7jcaupbs6m4ud", no encryption

My code is:

import psycopg2

conn = psycopg2.connect( dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

conn.close()

I look forward to receiving an answer.

I tried to use DATABASE_URL but don't work, either:

conn = psycopg2.connect(DATABASE_URL, sslmode='require')
Traceback (most recent call last): File "/home/aluno-di/Desktop/dbaccess.py", line 9, in <module>
DATABASE_URL = os.environ['postgres://hdyarfoicbluoo:[email protected]:5432/d7jcaupbs6m4ud'] File "/usr/lib/python3.8/os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'postgres://hdyarfoicbluoo:[email protected]:5432/d7jcaupbs6m4ud'

CodePudding user response:

In the first case you are missing the sslmode argument:

conn = psycopg2.connect(
    dbname=DB_NAME,
    user=DB_USER,
    password=DB_PASS,
    host=DB_HOST,
    sslmode="require",  # <-- Here
)

But it is better to use the DATABASE_URL environment variable, as you try to do in your second example. Heroku may change your database credentials at any time, and always using this variable is the best way to ensure that your application continues to work.

The whole point of storing connection strings in environment variables is so you don't have to put them directly in your code. Use the name of the environment variable to retrieve its value.

Something like this should work:

DATABASE_URL = os.environ["DATABASE_URL"]

conn = psycopg2.connect(DATABASE_URL)
  • Related