Scott Chapman
scott_list at mischko.com
Fri Dec 9 17:33:35 EST 2005
Daniel J. Popowich wrote: > Scott Chapman writes: > >>Mod_Python has a StringField class and psycopg2 can't seem to adapt it >>correctly. Type(stringfield_string) shows as: >><class 'mod_python.util.StringField'> >> >>Strings of this class have 3 extra items in dir(stringfield_string) which >>regular strins don't have: >>'__dict__', '__module__', 'value' >> >>Here's the class definition from mod_python.util: >>class StringField(str): >> """ This class is basically a string with >> a value attribute for compatibility with std lib cgi.py >> """ >> >> def __init__(self, str=""): >> str.__init__(self, str) >> self.value = self.__str__() >> >>How do I make psycopg2 deal with these correctly? It seems like >>there's a way to make custom "adapters" but I'm rather clueless >>here. I just need psycopg2 to run str() on the StringField instance >>and it'd work great. > > > This is a pain, I know. I use psycopg extensively and have been > burned more than once. There's nothing you can really do at the > psycopg module (afaik), but it's easy enough in your code...you can do > one of a few things: > > 1. a pain, but use str() explicitly. > > 2. build your query strings using python string formatting, instead > of the parameters of the cursor.execute() method. E.g.: > > cur.execute("insert into mytable (col1, col5) > values ('%s', %d)" % (some_str, some_int)) > > the %s will automatically call __str__() if some_str is not a > str. > > 3. Are you still using mpservlets? (you were at one time) If you > use query_vars to process your forms, your instance variables are > converted to str automagically. In the attached servlet, > types.mps, if you call it with: types?field=abc&realstr=def the > output will be: > > field: abc > type(field): <class 'mod_python.util.StringField'> > realstr: def > type(realstr): <type 'str'> > You've got a good memory Daniel! I took what I wanted of mpservlets and made my own mod_python handler from it. Here's the fix action: import psycopg2 import psycopg2.extras import psycopg2.extensions import mod_python psycopg2.extensions.register_adapter(mod_python.util.StringField, psycopg2.extensions.QuotedString) Scott
|