Python / Mako: How to get Unicode strings or characters correctly?

I am trying to get Mako to display some string with Unicode characters:

tempLook=TemplateLookup(..., default_filters=[], input_encoding='utf8',output_encoding='utf-8', encoding_errors='replace')
...
print sys.stdout.encoding
uname=cherrypy.session['userName']
print uname
kwargs['_toshow']=uname
...
return tempLook.get_template(page).render(**kwargs)

Associated template file:

...${_toshow}...

And the result:

UTF-8
Deşghfkskhü
...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1: ordinal not in range(128)

I don’t think that the problem is with the line itself, since I can print it just fine.

Despite the fact that I played (a lot) with parameters input/output_encodingand default_filters, he always complains about the impossibility of decoding / encoding with the ascii codec.

So, I decided to try the example found in the documentation , and the following works “better”:

input_encoding='utf-8', output_encoding='utf-8'
#(note : it still raised an error without output_encoding, despite tutorial not implying it) 

WITH

${u"voix m’a réveillé."} 

And the result

voix mâ a réveillé

I just don't understand why this is not working. The magic coding comment doesn’t work either. All files are encoded using UTF-8.

I spent hours to no avail, am I missing something?

Update:

I have a simpler question:

, unicode, Mako Unicode, ? /render _unicode() .a >

+3
1

, UTF-8!= .

UTF-8 - , ASCII ISO 8859-1. :

inputstring.decode('utf-8') ( ). outputstring.encode('utf-8') ( ). Unicode ('this is a normal string'.decode('utf-8') == u'this is a normal string')

'foo' - , u'foo' - , "" ( ). SO , python , "" , "" . "ascii", : -)

+3

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


All Articles