Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to Postgresql using SSL from SqlAchemy+pg8000?

Connecting to postgres via pg8000 from SqlAlchemy worked fine until I enabled SSL on postgres.

db = create_engine('postgresql+pg8000://user:pass@hostname/dbname', echo=True).connect()

Now it seems to fail with:

File "/Library/Python/2.7/site-packages/pg8000/core.py", line 872, in __init__
raise InterfaceError("communication error", exc_info()[1])
sqlalchemy.exc.InterfaceError: (InterfaceError) ('communication error', error(61, 'Connection refused')) None None
like image 732
sorin Avatar asked Aug 02 '14 13:08

sorin


People also ask

How do I connect to PostgreSQL with SSL?

With SSL support compiled in, the PostgreSQL server can be started with SSL enabled by setting the parameter ssl to on in postgresql. conf. The server will listen for both normal and SSL connections on the same TCP port, and will negotiate with any connecting client on whether to use SSL .

Can you use SQLAlchemy with PostgreSQL?

PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns.

How do you check if SSL is enabled on Postgres?

Verify SSL is EnabledVerify the configuration file for Postgres has the ca file configured cat /db/postgresql/*/data/postgresql. conf | grep 'ssl' . If the configuration file shows SSL is on and the server indicated it was off you'll need to Restart PostgreSQL.


2 Answers

probably you need to add connect_args dict:

db = create_engine('postgresql+pg8000://user:pass@hostname/dbname', connect_args={'sslmode':'require'}, echo=True).connect()
like image 147
Evgeny Prokurat Avatar answered Sep 24 '22 15:09

Evgeny Prokurat


The accepted answer no longer works, at least with these versions:

Python                   3.9
pg8000                   1.19.5
SQLAlchemy               1.4.12

The pg8000 docs describe what you have to do. Use

engine = create_engine('postgresql+pg8000://user:password@host/db', 
                       connect_args={'ssl_context': True})

which passes the result of ssl.create_default_context() to the connection creator. If a custom SSL context is required, pass it as the value instead of True:

import ssl

ssl_context = ssl.SSLContext()
# Set attributes as required  ...

engine = create_engine('postgresql+pg8000://user:password@host/db', 
                       connect_args={'ssl_context': ssl_context})
like image 28
snakecharmerb Avatar answered Sep 24 '22 15:09

snakecharmerb