[FIXED] Get the current response headers set in a Tornado request handler

Issue

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 X-Y 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.


Solution

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.



Answered By - xyres
Answer Checked By - Willingham (Python.Easybugfix Volunteer)

Related Posts

Post a Comment