简体   繁体   English

Cherrypy和内容类型

[英]Cherrypy and content-type

I've got a cherrypy app and I'm trying to change response header Content-type. 我有一个cherrypy应用程序,并且试图更改响应标头的Content-type。 I'm trying to do that with cherrypy.response.header['Content-Type'] = 'text/plain'. 我正在尝试使用cherrypy.response.header ['Content-Type'] ='text / plain'。 Unfortunately I'm still getting 'text/html'. 不幸的是,我仍然得到'text / html'。 I want to have set one content type for ok request and another content type for error message. 我想为ok请求设置一种内容类型,为错误消息设置另一种内容类型。 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. 好的,还有更复杂的代码,在前面的注释中有cherrypy的配置。 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. 想象一下,在res变量中,保存到db是结果。 The problem is, that this completely ignores my settings in the if condition. 问题是,这完全忽略了if条件下的设置。 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 装饰器是设置内容类型的唯一方法,这就是它在那里的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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