Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to an URI in postgres

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

like image 753
Daan Bakker Avatar asked Mar 26 '13 09:03

Daan Bakker


People also ask

How do I connect to a postgres database using URI?

postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...] The URI scheme designator can be either postgresql:// or postgres:// . In TablePlus, when creating a new connection, you can choose to import directly from URI instead of filling in credentials manually.

How do I connect to PostgreSQL connection?

The default username for postgres is postgres. (If you are using Advanced Server it is enterprisedb.) On a Mac or Windows, you are able to connect to the default instance by simply hitting enter at the shell or command prompt when trying to run psql and keying in the password.

How do I connect to another user in PostgreSQL?

CREATE ROLE sa WITH LOGIN PASSWORD 'some-password. '; CREATE DATABASE master WITH OWNER sa; \c master; Now you are running this script using "psql" command line interface (CLI), so you get the message as below... CREATE ROLE CREATE DATABASE You are now connected to database "master" as user "postgres".


2 Answers

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 ) 
like image 137
joamag Avatar answered Sep 21 '22 13:09

joamag


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.

like image 20
kynan Avatar answered Sep 19 '22 13:09

kynan