Connect to an URI in postgres

后端 未结 2 1593
北荒
北荒 2021-02-03 18:20

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\         


        
相关标签:
2条回答
  • 2021-02-03 18:30

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

    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
    port = result.port
    connection = psycopg2.connect(
        database = database,
        user = username,
        password = password,
        host = hostname,
        port = port
    )
    
    0 讨论(0)
  • 2021-02-03 18:34

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

    0 讨论(0)
提交回复
热议问题