2013-03-26 55 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