Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a psycopg2 connection using environment variables?

I'm confused by the psycopg2 documentation where it says:

Also note that the same parameters can be passed to the client library using environment variables.

I would expect that if I have environment variables exported such that I can connect using psql, that I should be able to make a connection the same way using psycopg2. But that doesn't seem to be the case.

Running a completely fresh postgresql in a container for example:

$ docker port frosty_lichterman 5432
0.0.0.0:32768
$ export PGHOST=localhost PGUSER=postgres PGPORT=32768

I can now connect using psql without providing any explicit connection string:

$ psql -c 'select 1;'
 ?column?
----------
        1
(1 row)

But in python, I cannot:

>>> import psycopg2 as p
>>> c = p.connect()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/michaels/.local/share/virtualenvs/Apps-XhIvHnVr/lib/python2.7/site-packages/psycopg2/__init__.py", line 127, in connect
    raise TypeError('missing dsn and no parameters')
TypeError: missing dsn and no parameters

Even though I can connect using Python if I explicitly provide the connection string:

>>> c = p.connect('host=localhost user=postgres port=32768')
>>> s = c.cursor()
>>> s.execute('select 1;')
>>> s.fetchall()
[(1,)]

So then, what does the documentation mean? What is the idiomatic and correct way to use libpq environment variables to make a psycopg2 connection?

like image 320
kojiro Avatar asked Jan 29 '19 14:01

kojiro


People also ask

Can psycopg2 connect to MySQL?

Both MySQL and PostgreSQL are supported. You would use psycopg2 to connect to Postgres and e.g. MySQLdb to connect to MySQL. You also have to change the connection string.

What is the host in psycopg2 connect?

In your context of psycopg2 and PostgreSQL connection, the host normally means the IP address of the PostgreSQL server or the resolvable name of the PostgreSQL server such as DNS name if it has. If you are running linux server, the output of command hostname is unlikely to work in your case.

What is DSN psycopg2?

A DSN is a string with a specific data structure that describes a connection to a particular data source. Many Python scripts that use the psycopg2 adapter rely on DSN parameters to help identify the data source for a PostgreSQL connection.


1 Answers

Try passing an empty connection string: c = p.connect("").

https://github.com/psycopg/psycopg2/issues/767

like image 103
Chris Avatar answered Oct 04 '22 07:10

Chris