Connect to an URI in postgres

PythonPsycopg2

Python Problem Overview


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 strings I 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

Python Solutions


Solution 1 - Python

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.

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
)

Solution 2 - Python

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.

Solution 3 - Python

To update on this, Psycopg3 does actually include a way to parse a database connection URI.

Example:

import psycopg # must be psycopg 3

pg_uri = "postgres://jeff:[email protected]/db"
conn_dict =  psycopg.conninfo.conninfo_to_dict(pg_uri)

with psycopg.connect(**conn_dict) as conn:
  ...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaan BakkerView Question on Stackoverflow
Solution 1 - PythonjoamagView Answer on Stackoverflow
Solution 2 - PythonkynanView Answer on Stackoverflow
Solution 3 - PythonmikkelamView Answer on Stackoverflow