简体   繁体   中英

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. Note that any other header is being set properly.

Firefox开发者工具

What's going on?

It seems this is a 304 Not Modified response. Remember only the first 200 OK response contains Content-Type header. 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 . If you look into the source code of Tornado, you will find this in the comment of 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 . (if you want to send JSON as a different Content-Type , call set_header after calling write()).

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