From 8afae0233aee07615cae92ec08505400b390b879 Mon Sep 17 00:00:00 2001 From: Colton Leekley-Winslow Date: Fri, 17 Apr 2015 11:24:08 -0400 Subject: [PATCH] feat(response): Add get_header method Previously there was no way to check if a header had been set on a response, without accessing _headers which doesn't feel clean. This commit adds a get_header method on the response object for checking if a header is set. --- falcon/request.py | 2 +- falcon/response.py | 16 ++++++++++++++-- tests/test_headers.py | 4 +++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/falcon/request.py b/falcon/request.py index 74915a0..cdb287e 100644 --- a/falcon/request.py +++ b/falcon/request.py @@ -558,7 +558,7 @@ class Request(object): return (preferred_type if preferred_type else None) def get_header(self, name, required=False): - """Return a raw header value as a string. + """Retrieve the raw string value for the given header. Args: name (str): Header name, case-insensitive (e.g., 'Content-Type') diff --git a/falcon/response.py b/falcon/response.py index 9979300..4812815 100644 --- a/falcon/response.py +++ b/falcon/response.py @@ -245,11 +245,23 @@ class Response(object): self._cookies[name]["httponly"] = http_only def unset_cookie(self, name): - """Unset a cookie from the response - """ + """Unset a cookie in the response.""" if self._cookies is not None and name in self._cookies: del self._cookies[name] + def get_header(self, name): + """Retrieve the raw string value for the given header. + + Args: + name (str): Header name, case-insensitive. Must be of type ``str`` + or ``StringType``, and only character values 0x00 through 0xFF + may be used on platforms that use wide characters. + + Returns: + str: The header's value if set, otherwise ``None``. + """ + return self._headers.get(name.lower(), None) + def set_header(self, name, value): """Set a header for this response to a given value. diff --git a/tests/test_headers.py b/tests/test_headers.py index 654eee9..783e59d 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -361,7 +361,7 @@ class TestHeaders(testing.TestBase): content_location = ('content-location', '/%C3%A7runchy/bacon') self.assertIn(content_location, self.srmock.headers) - def test_response_set_header(self): + def test_response_set_and_get_header(self): self.resource = HeaderHelpersResource() self.api.add_route(self.test_route, self.resource) @@ -370,11 +370,13 @@ class TestHeaders(testing.TestBase): content_type = 'x-falcon/peregrine' self.assertIn(('content-type', content_type), self.srmock.headers) + self.assertEquals(self.resource.resp.get_header('content-TyPe'), content_type) self.assertIn(('cache-control', 'no-store'), self.srmock.headers) self.assertIn(('x-auth-token', 'toomanysecrets'), self.srmock.headers) self.assertEqual(None, self.resource.resp.location) + self.assertEquals(self.resource.resp.get_header('not-real'), None) # Check for duplicate headers hist = defaultdict(lambda: 0)