leforestier / yattag

Python library to generate HTML or XML in a readable, concise and pythonic way.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UnicodeDecodeError: 'ascii' codec can't decode byte

21h opened this issue · comments

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())

added to my program this:

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

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())