如何使用环境变量建立 psycopg2 连接? [英] How can I make a psycopg2 connection using environment variables?

查看:59
本文介绍了如何使用环境变量建立 psycopg2 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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:

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

这篇关于如何使用环境变量建立 psycopg2 连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆