[pyar] Problema con encoding

Andrés Gattinoni andresgattinoni en gmail.com
Mar Jul 26 12:12:16 ART 2011


2011/7/25 Mariano Reingart <reingart en gmail.com>:
> Ese template se parece mucho al de web2py, y lo podes usar de forma
> separada, por ej:
>
>>>> from gluon import template
>>>> template.render("<h1>{{='hola %s' % nombre}}</h1>", context={'nombre': 'mariano'})
> '<h1>hola mariano</h1>'

Probé usando el módulo template de web2py pero me pasa algo qué no
entiendo bien por qué.
Tengo este código:

import sys
import codecs
from gluon import template

def render (filename, template_file, data):
    tplfile = codecs.open(template_file, 'r', 'utf-8')
    html = tplfile.read()
    tplfile.close()
    #f = codecs.open(filename, 'w', 'utf-8')
    f = open(filename, 'w')
    rendered = template.render(html, context=data)
    print rendered
    f.write(rendered)
    f.close()

Si lo ejecuto así, cuando hago "print rendered" se imprime sin
problemas, aunque las variables pareciera no estar procesándolas
(capaz está mal la sintaxis de mi template). Pero el archivo que
escribo se me escribe con data binaria que no puedo leer con el vim
(bueno, lo puedo leer, pero me muestra infinitas @).

En cambio si cambio la línea del open(filename, 'w') por la que lo
abre como utf-8 me tira el siguiente error:

Traceback (most recent call last):
  File "process.py", line 66, in <module>
    sys.exit(main(sys.argv))
  File "process.py", line 63, in main
    render('./index.html', 'templates/index.tpl', data)
  File "process.py", line 15, in render
    f.write(rendered)
  File "/usr/lib/python2.7/codecs.py", line 691, in write
    return self.writer.write(data)
  File "/usr/lib/python2.7/codecs.py", line 351, in write
    data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position
3352: ordinal not in range(128)

Probé reemplazando la línea 15 por:

f.write(rendered.decode('utf8'))

Pero ahí me dice:

Traceback (most recent call last):
  File "process.py", line 66, in <module>
    sys.exit(main(sys.argv))
  File "process.py", line 63, in main
    render('./index.html', 'templates/index.tpl', data)
  File "process.py", line 15, in render
    f.write(rendered.decode('utf8'))
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position
3352: invalid continuation byte

No entiendo por qué un string puedo imprimirlo sin problemas, pero
cuando lo quiero escribir en una archivo se rompe todo.
Qué se me está escapando?



More information about the pyar mailing list