[Tutor] cgi's + unicode

Gus Mueller gus at mu.org
Sun Sep 14 13:19:51 EDT 2003


I'm having a problem running a python cgi script, and gathering unicode
data-

I've looked at the faq, and tried a bunch of different ways to convert
the strings around and such, but nothing seems to work 100% of the time.

In this simple example (broken down from a bigger script), I just want a
user to enter unicode data into my text field, and have it displayed
right back to him/her.  Seems simple, but I keep on getting the error:
UnicodeError : ASCII encoding error: ordinal not in range(128) 

Has anyone been down this road, and successfully dealt with it?  (btw,
I'm running python 2.2.3)

#!/usr/bin/python

import string, os, sys, cgi
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# this throws an error..
#sys.setdefaultencoding("utf-8")


def getFormValue(name, default):
    
    formValue = form.getvalue(name, default)
    
    #just set a default value
    ret = formValue
    
    try:
        ret = unicode(formValue, "ascii")
    except UnicodeError:
        ret = unicode(formValue, "utf8")
    else:
        # value was valid ASCII data
        pass 
    
    return ret


print "Content-type: text/html; charset=utf-8\r\n"

blah = getFormValue("blah", "Zilch.")


print  u"""
    <form method="post" action="test.py">
    <input type="text" name="blah" value="%s" />
    <input type="submit" value="save" />
    </form>
    """ % blah
    
thanks,

-gus

--   
August Mueller
http://flyingmeat.com/
VoodooPad - 1st Place U.S., Second O'Reilly Mac OS X Innovaters Contest
"Christmas means carnage!"  -- Ferdinand, the duck



More information about the Tutor mailing list