简体   繁体   English

如何使用环境变量建立psycopg2连接?

[英]How can I make a psycopg2 connection using environment variables?

I'm confused by the psycopg2 documentation where it says: 我对psycopg2文档感到困惑,它说:

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. 我希望如果我导出了环境变量,以便我可以使用psql进行连接,那么我应该可以使用psycopg2以相同的方式建立连接。 But that doesn't seem to be the case. 但事实似乎并非如此。

Running a completely fresh postgresql in a container for example: 在容器中运行一个完全新鲜的postgresql,例如:

$ 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连接而不提供任何显式连接字符串:

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

But in python, I cannot: 但在python中,我不能:

>>> 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: 即使我可以使用Python连接,如果我明确提供连接字符串:

>>> 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? 使用libpq环境变量进行psycopg2连接的惯用和正确方法是什么?

Try passing an empty connection string: c = p.connect("") . 尝试传递一个空连接字符串: c = p.connect("")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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