Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-Type header not getting set in Tornado

Tags:

python

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 developer tools

What's going on?

like image 322
sssilver Avatar asked Jan 08 '23 06:01

sssilver


1 Answers

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()).

like image 144
skyline75489 Avatar answered Jan 14 '23 17:01

skyline75489