From 49da9ab57e61e8b6d14ea72b5256555cb5c41cb5 Mon Sep 17 00:00:00 2001 From: Malcolm Tredinnick Date: Sun, 2 Dec 2007 15:27:29 +0000 Subject: [PATCH] Fixed #6087 -- Added setdefault() support to the Session object. Thanks, Ben Slavin. git-svn-id: http://code.djangoproject.com/svn/django/trunk@6831 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/contrib/sessions/backends/base.py | 8 ++++++++ django/contrib/sessions/tests.py | 5 +++++ docs/sessions.txt | 2 ++ 3 files changed, 15 insertions(+) diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py index 192065a5f3..b8726fd2bd 100644 --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -51,6 +51,14 @@ class SessionBase(object): self.modified = self.modified or key in self._session return self._session.pop(key, *args) + def setdefault(self, key, value): + if key in self._session: + return self._session[key] + else: + self.modified = True + self._session[key] = value + return value + def set_test_cookie(self): self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE diff --git a/django/contrib/sessions/tests.py b/django/contrib/sessions/tests.py index ab3034f858..10bec9668b 100644 --- a/django/contrib/sessions/tests.py +++ b/django/contrib/sessions/tests.py @@ -66,6 +66,11 @@ False >>> s.accessed, s.modified (True, False) +>>> s.setdefault('foo', 'bar') +'bar' +>>> s.setdefault('foo', 'baz') +'bar' + >>> s.accessed = False # Reset the accessed flag >>> s.pop('some key') diff --git a/docs/sessions.txt b/docs/sessions.txt index 96e8d36854..eddc3f174a 100644 --- a/docs/sessions.txt +++ b/docs/sessions.txt @@ -99,6 +99,8 @@ It implements the following standard dictionary methods: * ``items()`` + * ``setdefault()`` + It also has these three methods: * ``set_test_cookie()``