【问题标题】:Connect to an URI in postgres连接到 postgres 中的 URI
【发布时间】:2013-03-26 09:58:20
【问题描述】:

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

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

出现以下错误:

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

有什么想法吗?根据the docs about connection strings,我相信它应该可以工作,但它只是这样:

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

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

【问题讨论】:

    标签: python psycopg2


    【解决方案1】:

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

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

    【讨论】:

    • 我很欣赏这个想法,但我希望找到更通用的东西,可以接受 postgres 可以接受的任何 RFC 3986 URI。
    • 我想这是你必须忍受的某种 psycop2 限制
    • 我终于找到了问题所在。是否支持 URI 连接字符串不取决于您的 PostgresQL 版本(而不取决于您的 psycopg2 版本)。我正在运行不支持它们的 PostgresQL 版本 9.1。
    • @Daan 的这个建议解决了我的问题,谢谢!如果可以选择升级到更新版本的 postgres,请执行此操作。另外,请注意,您必须在升级 postgres 后删除(例如pip uninstall psycopg2)然后重新安装(例如pip install psycopg2)。
    • 我不认为这取决于 PostgreSQL 版本,而是 psycopg2 使用的 libpq 版本。
    【解决方案2】:

    传递给psycopg2.connect 的连接字符串未被psycopg2 解析:它被逐字传递给libpqSupport for connection URIs was added in PostgreSQL 9.2.

    【讨论】:

      【解决方案3】:

      为了更新这一点,Psycopg3 实际上包含了一种解析数据库连接 URI 的方法。

      例子:

      import psycopg # must be psycopg 3
      
      pg_uri = "postgres://jeff:hunter2@example.com/db"
      conn_dict =  psycopg.conninfo.conninfo_to_dict(pg_uri)
      
      with psycopg.connect(**conn_dict) as conn:
        ...
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-15
        • 2014-08-15
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多