简体   繁体   中英

Cherrypy and content-type

I've got a cherrypy app and I'm trying to change response header Content-type. I'm trying to do that with cherrypy.response.header['Content-Type'] = 'text/plain'. Unfortunately I'm still getting 'text/html'. I want to have set one content type for ok request and another content type for error message. The only way how can I change content type is with my decorator. But this set type for the method and I need to change it. Do you know where could be a problem? My config:

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}
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}

Ok, there is more complex code, config of cherrypy is in the previous comment. I have a generator, which yields me some data and this is streaming that data in file to the client. I know, there are definitely better solutions. Imagine that in res variable there is result from saving to db. The problem is, that this completely ignores my settings in the if condition. It's still returning a file (empty one). The decorator is the only way how to set content type, that's why it's there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM