Content-Type header not 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 next 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 is pretty simple, except for Content-Type, it is not installed. Please note that any other header is set correctly.
What's happening?
source to share
This seems to be the answer 304 Not Modified
. Remember, only the first response 200 OK
contains a title Content-Type
. The following answer will ignore this header if you are requesting the same resource.
And be careful that you don't really need to explicitly install Content-Type
. If you look at the source code of Tornado, you will find it in the comment write(self, chunk)
:
If the given snippet is a dictionary, we write it as JSON and set the Content-Type of the response
application/json
. (if you want to send JSON as anotherContent-Type
, call set_header after call to write ()).
source to share