1

I'd like to connect ElephantSQL with Python.

import os
import psycopg2
import urlparse

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ["MY_DATABASE_URL"])

conn = psycopg2.connect(database=url.path[1:],
  user=url.username,
  password=url.password,
  host=url.hostname,
  port=url.port
)

but i get error:

Traceback (most recent call last): File "test.py", line 217, in url = urlparse.urlparse(os.environ["MY_DATABASE_URL"]) File "/usr/lib/python2.7/UserDict.py", line 23, in getitem raise KeyError(key) KeyError: 'MY_DATABASE_URL'

as my_database_url i write url from ElephantSQL (postgres://my_username:my_password@my_hostname/my_databasename)

What am I doing wrong?

Krasnal
  • 85
  • 2
  • 9

3 Answers3

2

I used:

conn = psycopg2.connect("dbname='my_dbname' user='my_user' host='my_host' password='my_password'")

and it's working now.

Krasnal
  • 85
  • 2
  • 9
0

I have tried the ElephantSQL documentation but the urllib.parse step did not work. I added the psycopg2.connect parameters directly as the solution above suggested following the ElephantSQL documentation syntax.

postgres://username:password@hostname:port/database

import psycopg2

conn = psycopg2.connect(database="database", user="username", password="password", host="hostname", port="port")
Luis Vargas
  • 321
  • 2
  • 8
0

I used this code

url = up.urlparse("DATABASE_URL")

instead of url = up.urlparse(os.environ["DATABASE_URL"]) code that you found ElephantSQL documentation

then I used

conn = psycopg2.connect(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port )

after that, I am able to connect elephantsql instance