leforestier / yattag

Python library to generate HTML or XML in a readable, concise and pythonic way.
333 stars 31 forks source link

UnicodeDecodeError: 'ascii' codec can't decode byte #22

Closed 21h closed 9 years ago

21h commented 9 years ago

Trying to text('Статистика '+runTime) (russian lang), but lib not want to do it

Traceback (most recent call last): File "./statistics.py", line 87, in file_.write(doc.getvalue()) File "/usr/local/lib/python2.7/dist-packages/yattag/doc.py", line 431, in getvalue return ''.join(self.result) UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

Code:

doc, tag, text = Doc().tagtext()
doc.asis('<!DOCTYPE html>')
with tag('html'):
    with tag('body'):
        text('Статистика '+runTime)
        with tag('table', border='1'):
            with tag('tr'):
                with tag('th'):
                    text('Name')
                with tag('th'):
                    text('Downloaded')
            for fileData in container:
                if fileData['content_type'] != 'application/directory':
                    with tag('tr'):
                        with tag('td'):
                            text(fileData['name'])
                        with tag('td'):
                            text(str(fileData['downloaded']))
with open(exportDirContainer+'/index.html', 'w') as file_:
    file_.write(doc.getvalue())
21h commented 9 years ago

added to my program this:

import sys
reload(sys)
sys.setdefaultencoding('utf8')

leforestier commented 9 years ago

Hi, with python 2, if you're saving your source files in another encoding than ascii, you must declare the encoding at the top of the file. If, in your text editor, you save the file with an UTF-8 encoding, you must add the following header to your source file:

# -*- coding: utf-8 -*-

This snippet works for me:

# -*- coding: utf-8 -*-

from yattag import Doc

doc, tag, text = Doc().tagtext()
doc.asis('<!DOCTYPE html>')
with tag('html'):
    with tag('body'):
        text('Статистика '+ 'some text')
        with tag('table', border='1'):
            with tag('tr'):
                with tag('th'):
                    text('Name')
                with tag('th'):
                    text('Downloaded')

print(doc.getvalue())