Haikson
@Haikson

Как в python wsgi вывести unicode?

Собственно код:
def app(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/html')])
    with codecs.open("template.html", 'r', 'utf8') as template_file:
        template_content = template_file.read()
    return template_content


И пустой ответ сервера
GET / => generated 0 bytes in 1 msecs (HTTP/1.1 200) 1 headers in 44 bytes (1105 switches on core 0)


Документ пустой.
Если template_content заменить на u"Привет" - то же самое. "Привет" - ответ нормальный.
return str(template_content) выдает ошибку кодировки
UnicodeEncodeError: 'ascii' codec can't encode characters in position 82-86: ordinal not in range(128)
  • Вопрос задан
  • 213 просмотров
Решения вопроса 1
@deliro
Application WSGI должен возвращать итерируемый объект, элементами которого являются байты.

from wsgiref.simple_server import make_server

def app(env, start_response):
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    text = '漢字'
    return ['{}: {}\n'.format(k,v).encode() for k,v in env.items()] + [text.encode()]

if __name__ == '__main__':
    with make_server('', 8000, app) as httpd:
        httpd.serve_forever()


UPD: Как в python wsgi вывести unicode?
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы