简体   繁体   English

在Tornado中未设置Content-Type标头

[英]Content-Type header not getting set in Tornado

I have the following base class: 我有以下基类:

class CorsHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        super(CorsHandler, self).set_default_headers()

        self.set_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '*'))
        self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
        self.set_header('Access-Control-Allow-Credentials', 'true')
        self.set_header('Access-Control-Allow-Headers', ','.join(
            self.request.headers.get('Access-Control-Request-Headers', '').split(',') +
            ['Content-Type']
        ))

        self.set_header('Content-Type', 'application/json')

    def options(self, *args, **kwargs):
        pass

And the following handler: 以下处理程序:

def get(self, resource_id=None, field=None):
    try:
        if resource_id is None:
            response = self.resource.query.filter_by(is_deleted=False).all()

        else:
            record = self.resource.query.get(int(resource_id))

            if field is None:
                response = record
            else:
                response = {field: getattr(record, field)}

        self.db.session.commit()

    except Exception, e:
        self.db.session.rollback()

        self.send_error(500, message=e.message)

    self.write(response)

Everything's pretty straightforward, except Content-Type is not getting set. 一切都很简单,除了Content-Type没有设置。 Note that any other header is being set properly. 请注意,正确设置了任何其他标头。

Firefox开发者工具

What's going on? 这是怎么回事?

It seems this is a 304 Not Modified response. 看来这是一个304 Not Modified响应。 Remember only the first 200 OK response contains Content-Type header. 请记住,只有前200 OK响应包含Content-Type标头。 The following response will neglect this header if you are requesting the same resource. 如果您请求相同的资源,以下响应将忽略此标头。

And beware that you don't actually need to explicitly set the Content-Type . 请注意,您实际上并不需要显式设置Content-Type If you look into the source code of Tornado, you will find this in the comment of write(self, chunk) : 如果你查看Tornado的源代码,你会在write(self, chunk)的注释中找到它:

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json . 如果给定的块是字典,我们将其写为JSON并将响应的Content-Type设置为application/json (if you want to send JSON as a different Content-Type , call set_header after calling write()). (如果要将JSON作为不同的Content-Type ,请调用write() 之后调用set_header)。

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

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