Python psycopg2 error vars function

2019-05-31 00:10发布

问题:

I have a piece of code that work fine on a server and don't work on other server ( Linux servers)

import psycopg2,psycopg2.extras
conn = psycopg2.connect("host=xx.x.x.x dbname=dev user=user password=pass" )
parentId='272'
dbCur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
dbCur.execute('select * from "treeItem" where "parentId" = %s order by "order"',(parentId,))
for row in dbCur:
    print type(row)
    print row.__dict__
    vars(row)
dbCur.close()
conn.close()

The output on the server error is :

class 'psycopg2.extras.Record'
Traceback (most recent call last):
  File "test1.py", line 8, in <module>
    print row.__dict__
AttributeError: 'Record' object has no attribute '__dict__'

but it work on the other server without problem. Same version of python (2.7) and psycopg2 2.5

How class psycopg2.extras.Record can have __dict__ on an environment and not in other?

Edit
Work on python 2.7.3 and psycopg2 2.5 (dt dec pq3 ext)
Dont work on python 2.7.5 psycopg2 2.5.1 (dt dec pq3 ext)

回答1:

You are using a psycopg2.extras.NamedTupleCursor, which produces instances of a class produced with the collections.namedtuple() class factory. These classes use __slots__ to limit their memory use.

Normally, classes with __slots__ don't have a __dict__ attribute. However, in Python 2.7.3 a __dict__ property was added (see revision 26d5f022eb1a), specifically to support vars() use. A later change removed the support again from Python 2.7.5, then it was readded for Python 2.7.6. The property acts as a proxy, calling namedtuple._asdict() to produce an OrderedDict object.

You have a Python 2.7.x release that doesn't have the property; e.g. one of 2.7, 2.7.1, 2.7.2 or 2.7.5. You can work around this by calling the namedtuple._asdict() method instead:

for row in dbCur:
    print type(row)
    print row._asdict()