From 059c9ab24c41e1460fd8b7af65ea8d5f80f1aa82 Mon Sep 17 00:00:00 2001 From: Sergey Parkhomenko Date: Thu, 11 Dec 2014 00:25:05 +0200 Subject: [PATCH] Fixed #23977 -- Added setdefault() method to HttpResponse --- django/http/response.py | 5 +++++ docs/ref/request-response.txt | 6 ++++++ docs/releases/1.8.txt | 4 ++++ tests/responses/tests.py | 14 ++++++++++++++ 4 files changed, 29 insertions(+) diff --git a/django/http/response.py b/django/http/response.py index 3edf10d1e8..2735e3c59d 100644 --- a/django/http/response.py +++ b/django/http/response.py @@ -261,6 +261,11 @@ class HttpResponseBase(six.Iterator): if httponly: self.cookies[key]['httponly'] = True + def setdefault(self, key, value): + """Sets a header unless it has already been set.""" + if key not in self: + self[key] = value + def set_signed_cookie(self, key, value, salt='', **kwargs): value = signing.get_cookie_signer(salt=key + salt).sign(value) return self.set_cookie(key, value, **kwargs) diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index 3ae8510ce8..3f4d371df5 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -708,6 +708,12 @@ Methods Returns ``True`` or ``False`` based on a case-insensitive check for a header with the given name. +.. method:: HttpResponse.setdefault(header, value) + + .. versionadded:: 1.8 + + Sets a header unless it has already been set. + .. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False) Sets a cookie. The parameters are the same as in the diff --git a/docs/releases/1.8.txt b/docs/releases/1.8.txt index 6635d625bb..5ab42996ab 100644 --- a/docs/releases/1.8.txt +++ b/docs/releases/1.8.txt @@ -483,6 +483,10 @@ Requests and Responses like :meth:`~django.http.HttpResponse.getvalue` so that instances can be used as stream objects. +* The new :meth:`HttpResponse.setdefault() + ` method allows setting a header unless + it has already been set. + Tests ^^^^^ diff --git a/tests/responses/tests.py b/tests/responses/tests.py index 9642790b9a..892c09b857 100644 --- a/tests/responses/tests.py +++ b/tests/responses/tests.py @@ -33,6 +33,20 @@ class HttpResponseBaseTests(SimpleTestCase): with self.assertRaisesMessage(IOError, 'This HttpResponseBase instance cannot tell its position'): r.tell() + def test_setdefault(self): + """ + HttpResponseBase.setdefault() should not change an existing header + and should be case insensitive. + """ + r = HttpResponseBase() + + r['Header'] = 'Value' + r.setdefault('header', 'changed') + self.assertEqual(r['header'], 'Value') + + r.setdefault('x-header', 'DefaultValue') + self.assertEqual(r['X-Header'], 'DefaultValue') + class HttpResponseTests(SimpleTestCase): def test_status_code(self):