2017-02-17 3 views
0

cherrypy 앱이 있는데 응답 헤더 Content-type을 변경하려고합니다. 나는 cherrypy.response.header [ 'Content-Type'] = 'text/plain'으로 해보려고합니다. 불행히도 나는 여전히 'text/html'을 얻고있다. ok 요청에 대해 하나의 콘텐츠 형식을 설정하고 오류 메시지에 대해 다른 콘텐츠 형식을 설정하려고합니다. 콘텐츠 유형을 어떻게 바꿀 수있는 유일한 방법은 내 데코레이터입니다. 그러나이 메서드에 대한 집합 형식 및이를 변경해야합니다. 어디서 문제가 될 수 있는지 아십니까? 내 설정 :Cherrypy 및 content-type

config = { 
    '/': { 
     'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 
     'tools.response_headers.on': True, 
     'tools.response_headers.headers': [('Content-Type', 'text/html')], 
    } 
} 



def GET(self, id): 
    cherrypy.response.headers['Content-Type'] = 'application/x-download' 
    somecode 
    if res < None: 
     cherrypy.response.headers['Content-Type'] = 'text/plain'   
     cherrypy.response.status=404 

GET._cp_config = {'response.stream': True} 
+0

'404 Not Found'에 대한 사용자 정의 응답을 보내려고하십니까? 이것을 확인하십시오 : https://github.com/cherrypy/cherrypy/blob/master/cherrypy/_cperror.py#L49-L111 맞춤 응답을 생성하기 위해 맞춤식 호출 가능을 설정할 수 있습니다. – webKnjaZ

+0

불행히도 작동하지 않습니다. 나는 cherrypy.expose()로 플레이하려고 노력했으며 행동은 약간 변하고있다. 아무도 날 어떻게 설명 할 수 있습니까? – George

+0

정확히 무엇입니까? 달성하려는 내용에 대해 자세히 설명하고보다 완전한 코드 스 니펫을 제공하십시오. – webKnjaZ

답변

0
def stream(): 
def decorate(func): 
    def wrapper(*args, **kwargs): 
     name = time.strftime("%Y%m%d-%H%M%S") 
     cherrypy.response.headers['Content-Type'] = 'application/x-download' 
     cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="' + name + '.txt"' 
     cherrypy.response.headers['Transfer-Encoding'] = 'chunked' 
     return func(*args, **kwargs) 
    return wrapper 
return decorate 



    @cherrypy.expose 
    class Network: 
@stream() 
def GET(self, id): 
    source = my_generator() 
    for i in source: 
     if res < None: 
      cherrypy.response.headers['Content-Type'] = 'text/plain'   
      cherrypy.response.status=404 
      break 
     yield bytes(i) 

GET._cp_config = {'response.stream': True} 

확인은 cherrypy의 설정은 이전의 코멘트에 더 복잡한 코드가있다. 나는 데이터를 생성하는 생성기를 가지고 있으며,이 데이터를 파일로 클라이언트에 스트리밍하고있다. 나도 알아, 거기에 확실히 더 나은 솔루션입니다. res 변수에는 db에 저장 한 결과가 있다고 가정합니다. 문제는 if 조건에서 내 설정을 완전히 무시한다는 것입니다. 여전히 파일을 반환하고 있습니다 (빈 파일). 데코레이터가 컨텐트 유형을 설정하는 유일한 방법입니다. 그 이유는 여기에 있습니다.