Python 连接到 postgres 中的 URI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15634092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:35:24  来源:igfitidea点击:

Connect to an URI in postgres

pythonpsycopg2

提问by Daan Bakker

I'm guessing this is a pretty basic question, but I can't figure out why:

我猜这是一个非常基本的问题,但我不知道为什么:

import psycopg2
psycopg2.connect("postgresql://postgres:postgres@localhost/postgres")

Is giving the following error:

给出以下错误:

psycopg2.OperationalError: missing "=" after
"postgresql://postgres:postgres@localhost/postgres" in connection info string

Any idea? According to the docs about connection stringsI believe it should work, however it only does like this:

任何的想法?根据关于连接字符串的文档,我认为它应该可以工作,但它只是这样做:

psycopg2.connect("host=localhost user=postgres password=postgres dbname=postgres")

I'm using the latest psycopg2 version on Python2.7.3 on Ubuntu12.04

我在 Ubuntu12.04 上的 Python2.7.3 上使用最新的 psycopg2 版本

采纳答案by kynan

The connection string passed to psycopg2.connectis not parsed by psycopg2: it is passed verbatim to libpq. Support for connection URIs was added in PostgreSQL 9.2.

传递给的连接字符串psycopg2.connect不被解析psycopg2:它被逐字传递给libpqPostgreSQL 9.2 中添加了对连接 URI 的支持

回答by joamag

I would use the urlparsemodule to parse the url and then use the result in the connection method. This way it's possible to overcome the psycop2 problem.

我会使用urlparse模块来解析 url,然后在连接方法中使用结果。这样就可以克服 psycop2 问题。

import urlparse # for python 3+ use: from urllib.parse import urlparse
result = urlparse.urlparse("postgresql://postgres:postgres@localhost/postgres")
# also in python 3+ use: urlparse("YourUrl") not urlparse.urlparse("YourUrl") 
username = result.username
password = result.password
database = result.path[1:]
hostname = result.hostname
connection = psycopg2.connect(
    database = database,
    user = username,
    password = password,
    host = hostname
)