2013-03-26 24 views
19

我猜这是一个非常基本的问题,但我想不通为什么:连接到一个URI中Postgres的

import psycopg2 
psycopg2.connect("postgresql://postgres:[email protected]/postgres") 

是给下面的错误:

psycopg2.OperationalError: missing "=" after 
"postgresql://postgres:[email protected]/postgres" in connection info string 

任何理念?据the docs about connection strings我相信它应该工作,但它只做这样的:

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

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

回答

29

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

import urlparse # import urllib.parse for python 3+ 
result = urlparse.urlparse("postgresql://postgres:[email protected]/postgres") 
username = result.username 
password = result.password 
database = result.path[1:] 
hostname = result.hostname 
connection = psycopg2.connect(
    database = database, 
    user = username, 
    password = password, 
    host = hostname 
) 
+2

我很欣赏这个想法,但我希望找到一些更一般的接受任何'RFC 3986'URI postgres可以接受的东西。 – 2013-03-26 23:06:42

+1

我想这是某种psycop2限制,你必须忍受 – joamag 2013-03-27 01:33:16

+12

我终于找出问题所在。是否支持URI连接字符串不取决于你的'PostgresQL'版本(而不是你的'psycopg2'版本)。我正在运行不支持它们的PostgresQL版本9.1。 – 2013-04-18 13:57:59