UnicodeEncodeError in Mako Template

I have the following files

dummy.py

#!c:/Python27/python.exe -u

from mako import exceptions
from mako.template import Template

print "Content-type: text/html"
print

#VARIABLE = "WE" 
VARIABLE = "我们"
template = Template(filename='../template/dummy.html', output_encoding='utf8')
try:
    print template.render(VARIABLE=VARIABLE)
except:
    print exceptions.html_error_template().render()

dummy.html (saved in UTF-8 format)

hello world
哈罗世界
${VARIABLE}

I referred to the instruction http://www.makotemplates.org/docs/unicode.html

However i still get the error

UnicodeDecodeError: codec 'ascii' cannot decode byte 0xe6 at position 0: serial number not in range (128)

Anything I missed?

+3
source share
2 answers
template = Template(filename='../template/dummy.html', default_filters=['decode.utf8'], input_encoding='utf-8', output_encoding='utf-8')
+5
source

Yes, because you are trying to pass it to ASCII, which does not work. You should say use output_encoding:

Template(filename='../template/dummy.html', output_encoding='utf8')

And please, no naked exceptions. Add the exceptions you expect to catch.

+2

Source: https://habr.com/ru/post/1781401/


All Articles