Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

question from:https://stackoverflow.com/questions/66066231/get-the-current-response-headers-set-in-a-tornado-request-handler

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...