问题描述
我对 psycopg2 文档感到困惑它说:
另请注意,可以使用环境变量将相同的参数传递给客户端库.
我希望如果我导出了环境变量以便我可以使用 psql
进行连接,那么我应该能够使用 psycopg2 以相同的方式建立连接.但似乎并非如此.
例如在容器中运行一个全新的 postgresql:
$ docker port froty_lichterman 54320.0.0.0:32768$ export PGHOST=localhost PGUSER=postgres PGPORT=32768
我现在可以使用 psql 进行连接,而无需提供任何显式连接字符串:
$ psql -c '选择 1;'?柱子?----------1(1 行)
但在 python 中,我不能:
>>>将 psycopg2 导入为 p>>>c = p.connect()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中文件/home/michaels/.local/share/virtualenvs/Apps-XhIvHnVr/lib/python2.7/site-packages/psycopg2/__init__.py",第127行,连接raise TypeError('缺少 dsn 且没有参数')类型错误:缺少 dsn 且没有参数即使我可以使用 Python 连接,如果我明确提供连接字符串:
>>>c = p.connect('host=localhost user=postgres port=32768')>>>s = c.cursor()>>>s.execute('选择1;')>>>s.fetchall()[(1,)]那么,文档是什么意思?使用 libpq 环境变量建立 psycopg2 连接的惯用和正确方法是什么?
尝试传递一个空的连接字符串:c = p.connect("")
.
https://github.com/psycopg/psycopg2/issues/767
I'm confused by the psycopg2 documentation where it says:
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
这篇关于如何使用环境变量建立 psycopg2 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!