Search code examples
pythonpython-2.7web2pypython-unicode

exceptions.UnicodeEncodeError: 'ascii' codec can't encode character u'\xc3' in position 12: ordinal not in range(128)


I'm using web2py framework and i'm getting the error <type 'exceptions.UnicodeEncodeError'> 'ascii' codec can't encode character u'\xc3' in position 12: ordinal not in range(128) only if i try to use the string value of self.servidor['NOME_SERVIDOR'] inside web2py's INPUT html helper: INPUT(_name='NOME_SERVIDOR', _type='text', _value=self.servidor['NOME_SERVIDOR'], _readonly='true').

Yes, i'm using # -*- coding: utf-8 -*- on top of the file.

# coding=utf-8
from gluon.html import *


def exampleControllerFunction():
    class FormAvaliacao(object):
        def __init__(self):
            self.servidor = current.session.dadosServidor
            self.tipo = current.session.avaliacaoTipo

        @property
        def exampleError(self):
            return FORM(
                INPUT(_name='NOME_SERVIDOR', _type='text', _value=self.servidor['NOME_SERVIDOR'], _readonly='true')
            )

        @property
        def exampleOk(self):
            return self.servidor['NOME_SERVIDOR']

    form1 = FormAvaliacao().exampleError
    form2 = FormAvaliacao().exampleOk

    return dict(form=form1)

As an example, the above code represents two situations where the same unicode string behaves differently.

ps.: I'm using the same string on many other parts of my code, and it only became a problem inside an INPUT.


Solution

  • http://web2py.com/examples/static/epydoc/web2py.gluon.html-pysrc.html#

    When you initalize the Input class, it calls self._postprocessing(), which in turn calls str(self['_value']). This is likely where the error occurs.

    1766          if self['_value'] is None or isinstance(self['_value'],cgi.FieldStorage): 
    1767              _value = None 
    1768          else: 
    1769              _value = str(self['_value'])