The Tornado RequestHandler
class has add_header()
, clear_header()
, and set_header()
methods. Is there a way to just see the headers that are currently set?
My use case is that I am writing some utility methods to automatically set response headers under certain conditions. But I want to add some error checking in order to not add duplicates of a header that I do not want to have duplicated.
I want to write come code that is more or less like this:
class MyHandler(tornado.web.RequestHandler):
def ensure_json_header(self):
if not self.has_header_with_key('Content-Type'):
self.set_header('Content-Type', 'application/json')
def finish_json(self, data):
self.ensure_json_header()
return self.finish(json.dumps(data))
But of course there is no has_header_with_key()
method in Tornado. How can I accomplish this?
EDIT : this turned out to be an XY question. The real answer was to just use set_header
instead of add_header
. I am leaving this up for anyone else who might come along with a similar question.
There's no documented api for listing the headers present in a response.
But there is a self._headers
private attribute (an instance of tornado.httputil.HTTPHeaders
) which is basically a dict of all headers in the response. You can do this to check a header:
if 'Content-Type' in self._headers:
# do something
As an addendum, if you want to access all headers of a request, you can do self.request.headers
.
Edit: I've opened an issue about this on github after seeing your question; let's see what happens.
Tornado will always have the Content-Type
header set as it is in the default headers ( https://www.tornadoweb.org/en/stable/_modules/tornado/web.html#RequestHandler.clear ). So if you want to ensure you have a specific content type set, just call set_header
.
If you want to check that the response does not have a header set in your code , you'll have to first reset the default header, which you can do by implementing set_default_headers
and do a clear_header(“Content-Type”)
there.
But you could also achieve the same by setting a property on your handler (say override_content_type
), set that in code and then do a non conditional set_header
before rendering the result.
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.