2016-08-22 5 views
0

Content-Type 헤더를 수정하여 HTTP 응답 문자 세트를 지정하고 싶습니다. 그러나 작동하지 않습니다.CherryPy에서 강제 응답 문자 집합

다음은 간단한 예입니다

#coding=utf-8 
import cherrypy 

class Website: 
    @cherrypy.expose() 
    def index(self): 
     cherrypy.response.headers['Content-Type']='text/plain; charset=gbk' 
     return '。。。'.encode('gbk') 

cherrypy.quickstart(Website(),'/',{ 
    '/': { 
     'tools.response_headers.on':True, 
    } 
}) 

그리고 내가 그 페이지를 방문 할 때 Content-Type 브라우저에서 글자 깨짐의 원인, text/plain;charset=utf-8에 신비하게 변경됩니다.

C:\Users\Administrator>ncat 127.0.0.1 8080 -C 
GET/HTTP/1.1 
Host: 127.0.0.1:8080 

HTTP/1.1 200 OK 
Server: CherryPy/7.1.0 
Content-Length: 6 
Content-Type: text/plain;charset=utf-8 
Date: Mon, 22 Aug 2016 01:08:13 GMT 

。。。^C 

CherryPy가 콘텐츠 인코딩을 감지하고 자동으로 해당 문자셋을 무시하는 것으로 보입니다. 그렇다면 어떻게이 기능을 비활성화 할 수 있습니까?

답변

0

좋습니다. cherrypy.response.header_list을 직접 조작하여이 문제를 해결했습니다.

#coding=utf-8 
import cherrypy 

def set_content_type(): 
    header=(b'Content-Type',cherrypy.response._content_type.encode()) 

    for ind,(key,_) in enumerate(cherrypy.response.header_list): 
     if key.lower()==b'content-type': 
      cherrypy.response.header_list[ind]=header 
      break 
    else: 
     cherrypy.response.header_list.append(header) 

cherrypy.tools.set_content_type=cherrypy.Tool('on_end_resource',set_content_type) 

class Website: 
    @cherrypy.expose() 
    @cherrypy.tools.set_content_type() 
    def index(self): 
     cherrypy.response._content_type='text/plain; charset=gbk' 
     return '。。。'.encode('gbk') 

cherrypy.quickstart(Website(),'/') 
+0

당신은'tools.encode.encoding'와'tools.decode.encoding' http://docs.cherrypy.org/en/latest/config.html#environments – webKnjaZ

+0

아니라, 웹 사이트 내가 설정을 시도한다 내가 작업하는 것은 파일 공유 서버입니다. 즉, 인코딩이 파일마다 다릅니다. 그래서 나는 하드 코딩을 체리 피 설정으로 코딩 할 수 없다. – xmcp

+0

Cherrypy 설정은 클래스 또는 핸들러별로 무시 될 수 있습니다. 글로벌 일 필요는 없습니다. – webKnjaZ