简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM