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?
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.
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.
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.
Try passing an empty connection string: c = p.connect("")
.
https://github.com/psycopg/psycopg2/issues/767
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With