mirror of
https://github.com/django/django.git
synced 2025-08-03 10:34:04 +00:00
Fixed #12982 -- Added a get_or_set() method to the BaseCache backend.
This commit is contained in:
parent
a52cd407b8
commit
34fb909180
4 changed files with 64 additions and 1 deletions
|
@ -94,7 +94,8 @@ Minor features
|
|||
Cache
|
||||
^^^^^
|
||||
|
||||
* ...
|
||||
* ``django.core.cache.backends.base.BaseCache`` now has a ``get_or_set()``
|
||||
method.
|
||||
|
||||
Email
|
||||
^^^^^
|
||||
|
|
|
@ -778,6 +778,25 @@ If you need to know whether ``add()`` stored a value in the cache, you can
|
|||
check the return value. It will return ``True`` if the value was stored,
|
||||
``False`` otherwise.
|
||||
|
||||
If you want to get a key's value or set a value if the key isn't in the cache,
|
||||
there is the ``get_or_set()`` method. It takes the same parameters as ``get()``
|
||||
but the default is set as the new cache value for that key, rather than simply
|
||||
returned::
|
||||
|
||||
>>> cache.get('my_new_key') # returns None
|
||||
>>> cache.get_or_set('my_new_key', 'my new value', 100)
|
||||
'my new value'
|
||||
|
||||
You can also pass any callable as a *default* value::
|
||||
|
||||
>>> import datetime
|
||||
>>> cache.get_or_set('some-timestamp-key', datetime.datetime.now)
|
||||
datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)
|
||||
|
||||
.. versionchanged:: 1.9
|
||||
|
||||
The ``get_or_set()`` method was added.
|
||||
|
||||
There's also a ``get_many()`` interface that only hits the cache once.
|
||||
``get_many()`` returns a dictionary with all the keys you asked for that
|
||||
actually exist in the cache (and haven't expired)::
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue