2010-01-31 5 views
3

UTF-8로 인코딩 된 웹 브라우저에 HTML 페이지를 보내려고합니다. 다음 예는 실패하지만 : 나는 인코딩을 제거하고 단순히 파이썬 3 유니 코드 문자열을 반환하는 경우WSGI 출력을 UTF-8로 인코딩하는 방법은 무엇입니까?

Serving on 8000 
Traceback (most recent call last): 
    File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 75, in run 
    self.finish_response() 
    File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 116, in finish_response 
    self.write(data) 
    File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/wsgiref/handlers.py", line 202, in write 
    "write() argument must be a string or bytes" 

의 wsgiref 서버가 어떤 캐릭터 세트 브라우저 지정에 인코딩하는 것 같다 여기

from wsgiref.simple_server import make_server 

def app(environ, start_response): 
    output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8') 
    start_response('200 OK', [ 
     ('Content-Type', 'text/html'), 
     ('Content-Length', str(len(output))), 
    ]) 
    return output 

port = 8000 
httpd = make_server('', port, app) 
print("Serving on", port) 
httpd.serve_forever() 

는 역 추적입니다 요청 헤더에. 그러나 모든 WSGI 서버가 동일한 작업을 수행 할 것으로 기대할 수는 없으므로이 컨트롤을 직접 사용하고 싶습니다. UTF-8로 인코딩 된 HTML 페이지를 반환하려면 어떻게해야합니까?

감사합니다.

+0

당신의 출력이 유니 코드 문자해야해야) 그것을 인코딩. 아마 당신의 현재 문제의 원인이 아니지만 그것은 언젠가 엉덩이에 당신을 물 것입니다. –

+0

u'Räksmörgås '와 같은 문자열을 쓰는 것을 말하고 있습니까? 나는 파이썬 3에있는 것처럼 그렇게 할 필요가 없다. – pthulin

답변

5

당신은 목록으로 페이지를 반환해야합니다

def app(environ, start_response): 
    output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8') 
    start_response('200 OK', [ 
     ('Content-Type', 'text/html; charset=utf-8'), 
     ('Content-Length', str(len(output))) 
    ]) 

    return [output] 

WSGI 그런 식으로 설계 있도록 단지 yield되는 HTML (전체 또는 부분 중 하나) 할 수 있었다.

+0

충분히 공정하고 그것을 바꿨다. – AndiDog

+0

감사합니다. 결과를 목록으로 반환하여 해결했습니다! – pthulin

0

편집

vim /usr/lib/python2.7/site.py 

encoding = "ascii" # Default value set by _PyUnicode_Init() 

재부팅 시스템

encoding = "utf-8" 

파라 forcar 오 파이썬 2.7 trabalhar 닷컴 UTF-8 코모 padrão 관심 장소 오 mod_wsgi에 busca codificacao padrao 할 파이썬 가야 앤티 시대 ascii com 아니오 maximo 128 caracteres! (2

+1

너무 중요하지 않거나 관련이 없다면 마지막 단락을 영어로 번역하십시오. – Drew

0

AndiDog의 대답은 정확하지만 어떤 환경에서 당신은 응용 프로그램에 응용 프로그램을 변경 (1) 당신이 그것을하고 비 ASCII 문자를 사용하고 있기 때문에

def application(environ, start_response): 
    output = "<html><body><p>Räksmörgås</p></body></html>".encode('utf-8') 
    start_response('200 OK', [ 
     ('Content-Type', 'text/html; charset=utf-8'), 
     ('Content-Length', str(len(output))) 
    ]) 
    return [output] 
+0

이 질문에 대한 답을 제공하지 않습니다. 충분한 [평판] (https://stackoverflow.com/help/whats-reputation)이 있으면 [모든 게시물에 주석 달기] (https://stackoverflow.com/help/privileges/comment) 할 수 있습니다. 대신, [질문자의 설명이 필요없는 답변을 제공하십시오] (https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can- i-do- 대신). – Yaron