[mod_python] Why can't psycopg2 beta adapt this:

Daniel J. Popowich dpopowich at comcast.net
Fri Dec 9 12:20:50 EST 2005


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'>


Cheers,

Daniel Popowich
---------------
http://home.comcast.net/~d.popowich/mpservlets/


-------------- next part --------------
# -*- python -*-
from mod_python.servlet import HTMLPage

import cgi

class types(HTMLPage):
      
    query_vars = ['realstr']

    def prep(self):
        HTMLPage.prep(self)
        self.field = self.form.getfirst('field')
    
    def write_content(self):
        self.writeln('field: %s<br>' % self.field)

        self.writeln('type(field): %s<br>' %
                     cgi.escape(str(type(self.field))))

        self.writeln('realstr: %s<br>' % self.realstr)

        self.writeln('type(realstr): %s<br>' %
                     cgi.escape(str(type(self.realstr))))


More information about the Mod_python mailing list