thetaiko
thetaiko

Reputation: 7824

Unable to open a connection to PostgreSQL from Python3

I'm running into a weird problem where I'm unable to connect to PostgreSQL from a Python 3.2 install. I'm running Fedora 15 and have installed Python3 and PostgerSQL9 from the Fedora repositories using yum. Does anyone have any ideas on why I'm seeing this problem and how to correct it? Google searches haven't been turning up anything.

I've changed the username, password, and database, but my pg_hba.conf file is correct.

import postgresql
t = postgresql.open(user='validuser', password='secret', database='some_database')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.2/site-packages/postgresql/__init__.py", line 88, in open
    c.connect()
  File "/usr/lib64/python3.2/site-packages/postgresql/driver/pq3.py", line 2419, in connect
    pq = Connection3(sf, startup, password = password,)
  File "/usr/lib64/python3.2/site-packages/postgresql/protocol/client3.py", line 514, in __init__
    element.Startup(**startup), password
TypeError: keyword arguments must be strings

As a side note, I get this same error if I try to connect using different user, password, database combinations, and also if I use a pq://user:password@host/database connection string instead of keywords, both to localhost and to remote hosts.

Upvotes: 2

Views: 3069

Answers (3)

w.diesel
w.diesel

Reputation: 300

You can also use another module - psycopg2 to connect to postgresql

http://initd.org/psycopg/download/

Upvotes: 0

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37904

I think that probably is some bug in python3-postgresql package, but it looks like it works after little change. Edit this file (probably /usr/lib64 for 64 bit installations):

/usr/lib/python3.2/site-packages/postgresql/protocol/client3.py

Change (line 514):

element.Startup(**startup), password

to:

element.Startup(startup), password

After that I made simple connection (I changed pg_hba.conf host methods to md5) and it looks ok:

[grzegorz@localhost Desktop]$ python3
Python 3.2 (r32:88445, Feb 21 2011, 21:12:33) 
[GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import postgresql
>>> db = postgresql.open("pq://grzegorz:12345@localhost/grzegorz")
>>> ps = db.prepare("SELECT version()")
>>> ps()
[('PostgreSQL 9.0.4 on i386-redhat-linux-gnu, compiled by GCC gcc (GCC) 4.6.0 20110530 (Red Hat 4.6.0-9), 32-bit',)]
>>> ps = db.prepare("TABLE t")
>>> ps()
[(1, 'aaa'), (2, 'bbb'), (3, 'ccc')]
>>>

Upvotes: 4

Gerrat
Gerrat

Reputation: 29680

Just a guess, but python is probably passing unicode to postgres and it's expecting strings.

Upvotes: 0

Related Questions