Here are the examples of the python api django.core.cache.cache.set taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
170 Examples
3
Example 1
def increment_counter(obj):
"""
Invalidate the cache for the passed object.
"""
if obj is not None: # If the object is None, do nothing (it's pointless)
cache.set(counter_key(obj), int(time.time()), 1*HOUR)
3
Example 2
def test_get(self):
cache.set('foo', 'bar', 60)
cache.set('moof', 'baz', 1)
no_cache = NoCache()
self.assertEqual(no_cache.get('foo'), None)
self.assertEqual(no_cache.get('moof'), None)
self.assertEqual(no_cache.get(''), None)
3
Example 3
Project: transifex Source File: cache.py
def set_fragment_content(node, key_vars, context):
"""Set the rendered content of a template fragment."""
try:
for code, lang in settings.LANGUAGES:
cur_vars = list(key_vars)
cur_vars.append(unicode(code))
args = md5_constructor(u':'.join([urlquote(var) for var in cur_vars]))
cache_key = 'template.cache.%s.%s' % (node.fragment_name, args.hexdigest())
context['use_l10n'] = True
context['LANGUAGE_CODE'] = code
value = node.nodelist.render(context=Context(context))
cache.set(cache_key, value, settings.CACHE_MIDDLEWARE_SECONDS)
except Exception, e:
invalidate_template_cache(node.fragment_name, key_vars.keys())
3
Example 4
Project: django-mysql Source File: test_cache.py
@override_cache_settings(options={'MAX_ENTRIES': -1})
def test_cull_max_entries_minus_one(self):
# cull with MAX_ENTRIES = -1 should never clear anything that is not
# expired
# one expired key
cache.set('key', 'value', 0.1)
time.sleep(0.2)
# 90 non-expired keys
for n in six.moves.range(9):
cache.set_many({
str(n * 10 + i): True
for i in six.moves.range(10)
})
cache.cull()
assert self.table_count() == 90
3
Example 5
def _invalidate_cache(self, instance):
"""
Explicitly set a None value instead of just deleting so we don't have
any race conditions where.
"""
for key in instance.cache_keys:
cache.set(key, None, 5)
3
Example 6
def test_get(self):
cache.set('foo', 'bar', 60)
cache.set('moof', 'baz', 1)
simple_cache = SimpleCache()
self.assertEqual(simple_cache.get('foo'), 'bar')
self.assertEqual(simple_cache.get('moof'), 'baz')
self.assertEqual(simple_cache.get(''), None)
3
Example 7
Project: django Source File: tests.py
def test_filefield_pickling(self):
# Push an object into the cache to make sure it pickles properly
obj = Storage()
obj.normal.save("django_test.txt", ContentFile("more content"))
obj.normal.close()
cache.set("obj", obj)
self.assertEqual(cache.get("obj").normal.name, "tests/django_test.txt")
3
Example 8
def set(key, group, value, timeout):
"""Generates a cache key for a group item.
:param key: The key of the item to cache.
:param group: The name of the group.
:param value: The value that will be placed in the cache.
:param timeout: Timeout in seconds for the cached value.
"""
combined_key = generate_cache_key(key, group)
cache.set(combined_key, value, timeout)
3
Example 9
Project: django-versionedcache Source File: test_debug.py
def test_super_user_can_turn_cache_write_only(self):
c = self.client
c.login(username='super', password='supersecret')
cache.cache.set('key', 'some value')
c.post('/set/?cache_debug=write_only', {'key': 'other value'})
tools.assert_equals('other value', cache.cache.get('key'))
response = c.get('/get/key/', {'cache_debug': 'write_only'})
tools.assert_equals(repr(None), response.content)
tools.assert_equals('other value', cache.cache.get('key'))
3
Example 10
Project: django-cache-sweeper Source File: utils.py
def update_cache_token_for_record_with_attribute(instance, token_attr):
"""
Update the token with a value read from an attribute of the ORM's record
"""
cache_key = cache_token_key_for_record(instance)
token_value = getattr(instance,token_attr)
token_value_hash = md5_constructor(str(token_value)).hexdigest()
cache.set(cache_key, token_value_hash, 0) # 0 = no time based expiry
return token_value_hash
3
Example 11
Project: django-scribbler Source File: models.py
@receiver(post_delete, sender=Scribble)
def populate_scribble_cache(sender, instance, **kwargs):
"Populate cache with empty scribble cache on delete."
if CACHE_TIMEOUT:
key = CACHE_KEY_FUNCTION(slug=instance.slug, url=instance.url)
scribble = Scribble(slug=instance.slug, url=instance.url)
cache.set(key, scribble, CACHE_TIMEOUT)
3
Example 12
Project: django-test-mixins Source File: tests.py
def test_cache_emptied(self):
cache.set('foo', 1)
self.assertEqual(cache.get('foo'), 1, "Cache doesn't seem to be configured.")
class MyTestCase(EmptyCacheTestCase):
def runTest(self):
pass
test_case = MyTestCase()
test_case.setUp()
self.assertEqual(cache.get('foo'), None,
"Cache was not emptied during setUp!")
3
Example 13
Project: tendenci Source File: cache.py
def cache_all_robots():
""" Caches all query of robots """
from tendenci.apps.robots.models import Robot
keys = [settings.CACHE_PRE_KEY, CACHE_PRE_KEY, 'all']
key = '.'.join(keys)
robots = Robot.objects.all()
cache.set(key, robots)
3
Example 14
Project: teerace Source File: tasks.py
@task(ignore_result=True)
def update_yesterday_runs():
# everyday, around 0:00 AM
yesterday = datetime.today() - timedelta(days=1)
runs_yesterday = Run.objects.filter(created_at__range=
(datetime.combine(yesterday, time.min),
datetime.combine(yesterday, time.max)))
cache.set('runs_yesterday', runs_yesterday, timeout=None)
3
Example 15
Project: django-tracking Source File: listeners.py
def refresh_untracked_user_agents(sender, instance, created=False, **kwargs):
"""Updates the cache of user agents that we don't track"""
log.debug('Updating untracked user agents cache')
cache.set('_tracking_untracked_uas',
UntrackedUserAgent.objects.all(),
3600)
3
Example 16
Project: django-affect Source File: utils.py
def uncache_flag(**kwargs):
flag = kwargs.get('instance')
cache.set(FLAG_CONFLICTS_KEY % flag.name, None, 5)
for criteria in flag.criteria_set.all():
uncache_criteria(instance=criteria)
3
Example 17
Project: django-rest-framework Source File: test_renderers.py
def test_get_caching(self):
"""
Test caching of GET requests
"""
response = self.client.get('/cache')
cache.set('key', response)
cached_response = cache.get('key')
assert isinstance(cached_response, Response)
assert cached_response.content == response.content
assert cached_response.status_code == response.status_code
3
Example 18
def _cache_translation(translation, timeout=DEFAULT_TIMEOUT):
"""
Store a new translation in the cache.
"""
if not appsettings.PARLER_ENABLE_CACHING:
return
if translation.master_id is None:
raise ValueError("Can't cache unsaved translation")
# Cache a translation object.
# For internal usage, object parameters are not suited for outside usage.
fields = translation.get_translated_fields()
values = {'id': translation.id}
for name in fields:
values[name] = getattr(translation, name)
key = get_translation_cache_key(translation.__class__, translation.master_id, translation.language_code)
cache.set(key, values, timeout=timeout)
3
Example 19
def test_clicks(self):
cache.set(self.promo.cache_key(type=CLICKS, hash='random_hash'), 0)
resp = self.client.get(
'http://testserver/sustainability/click/%s/random_hash/' % self.promo.id)
self.assertEqual(resp._headers['location'][1], 'http://example.com')
promo = SupporterPromo.objects.get(pk=self.promo.pk)
impression = promo.impressions.first()
self.assertEqual(impression.clicks, 1)
3
Example 20
def get_async_progress(request, *args, **kwargs):
""" Returns the progress as json for use with ajax """
if 'runcode' in kwargs:
runcode = kwargs['runcode']
else:
session_runcode = request.session.get('runcode', None)
if session_runcode is not None:
runcode = session_runcode
runinfo = get_runinfo(runcode)
response = dict(progress=get_progress(runinfo))
cache.set('progress' + runinfo.random, response['progress'])
response = HttpResponse(json.dumps(response),
content_type='application/javascript');
response["Cache-Control"] = "no-cache"
return response
3
Example 21
@classmethod
def update_currencies(cls):
currency_list = Currency.objects.all()
for currency in currency_list:
currency.us_change = Currency.convert(currency.iso_code, 'USD')
currency.save()
# cache value for 25 hs
cache.set(currency.currency, currency.us_change,
CURRENCY_UPDATE_TIMEOUT)
3
Example 22
def process_request(self, request):
try:
if request.user.id:
cache.set(USER_TRACK_ACTIVE_KEY % request.user.id, "True", getattr(settings, 'PROFILE_ACTIVE_TIMEOUT',60))
cache.set(USER_TRACK_IDLE_KEY % request.user.id, "True", getattr(settings, 'PROFILE_ACTIVE_TIMEOUT',300))
except AttributeError:
logging.getLogger('django.request').error('user variable not available in request, make sure UserState is after auth in middleware list')
3
Example 23
def test_no_cookie(self):
mid = FooterNoSessionMiddleware()
factory = RequestFactory()
# Setup
cache.set(self.promo.cache_key(type=VIEWS, hash='random_hash'), 0)
request = factory.get(
'http://testserver/sustainability/view/%s/random_hash/' % self.promo.id
)
# Null session here
mid.process_request(request)
self.assertEqual(request.session, {})
# Proper session here
home_request = factory.get('/')
mid.process_request(home_request)
self.assertTrue(home_request.session.TEST_COOKIE_NAME, 'testcookie')
3
Example 24
def _post_save(self, instance, **kwargs):
"""
Refresh the cache when saving
"""
for key in instance.cache_keys:
cache.set(key, instance, CACHE_DURATION)
3
Example 25
Project: django-nginx-ssi Source File: nginxssi_tags.py
@register.tag
def nginxssi(parser, token):
tokens = token.split_contents()
# automatically generate key based on template code
template_string = render_raw_template(parser, token, 'endnginxssi')
cache_key = generate_ssi_cache_key(template_string)
if cache_key not in cache:
cache.set(cache_key, template_string)
return NginxSSINode(cache_key)
3
Example 26
Project: django-scribbler Source File: models.py
@receiver(post_save, sender=Scribble)
def update_scribble_cache(sender, instance, **kwargs):
"Update scribble cache on save."
if CACHE_TIMEOUT:
key = CACHE_KEY_FUNCTION(slug=instance.slug, url=instance.url)
cache.set(key, instance, CACHE_TIMEOUT)
3
Example 27
Project: dynamic-models Source File: utils.py
def notify_model_change(model):
""" Notifies other processes that a dynamic model has changed.
This should only ever be called after the required database changes have been made.
"""
CACHE_KEY = HASH_CACHE_TEMPLATE % (model._meta.app_label, model._meta.object_name)
cache.set(CACHE_KEY, model._hash)
logger.debug("Setting \"%s\" hash to: %s" % (model._meta.verbose_name, model._hash))
3
Example 28
Project: tendenci Source File: cache.py
def cache_reg_apps(apps):
"""Caches the list of registered apps
"""
keys = [settings.CACHE_PRE_KEY, REGISTRY_PRE_KEY, 'reg_apps']
key = '.'.join(keys)
value = apps.all_apps
cache.set(key, value)
3
Example 29
Project: django-mysql Source File: test_cache.py
@parameterized.expand(['default', 'prefix', 'custom_key', 'custom_key2'])
def test_keys_with_prefix_version(self, cache_name):
cache = caches[cache_name]
cache.set('V12', True, version=1)
cache.set('V12', True, version=2)
cache.set('V2', True, version=2)
cache.set('V3', True, version=3)
assert cache.keys_with_prefix('V', version=1) == {'V12'}
assert cache.keys_with_prefix('V', version=2) == {'V12', 'V2'}
assert cache.keys_with_prefix('V', version=3) == {'V3'}
3
Example 30
def handle(self, *args, **kwargs):
timeout = settings.FEATUREFLAGS_PANIC_TIMEOUT
flags = settings.FEATUREFLAGS_PANIC_DISABLE
if not flags:
self.stdout.write(
"You have not listed any disable-when-panicked features in settings.FEATUREFLAGS_PANIC_DISABLE. \n"
"Nothing to disable here. Please continue to panic.")
return
cache.set(cache_key, flags, timeout)
self.stdout.write("These features have been disabled for %s seconds:\n" % (timeout))
for f in flags:
self.stdout.write(" " + f)
self.stdout.write("Best of luck. You may return to normal operation by calling 'manage.py unpanic'.\n")
3
Example 31
Project: django-supertagging Source File: markup.py
def __get__(self, instance, owner):
if not instance:
return
data = self._get_cached_value(instance)
if data:
return data
try:
data = self.handle(instance)
except Exception, e:
data = getattr(instance, self.field)
if settings.ST_DEBUG: raise Exception(e)
cache.set(self._get_cache_key(instance), data, settings.MARKUP_CONTENT_CACHE_TIMEOUT)
return data
3
Example 32
def test_get(self):
cache.set('foo', 'bar', 60)
cache.set('moof', 'baz', 1)
no_cache = NoCache()
self.assertEqual(no_cache.get('foo'), None)
self.assertEqual(no_cache.get('moof'), None)
self.assertEqual(no_cache.get(''), None)
3
Example 33
@task(ignore_result=True)
def update_totals():
# every 15 minutes
total_runs = Run.objects.count()
total_runtime = Run.objects.aggregate(Sum('time'))['time__sum']
total_playtime = UserProfile.objects.aggregate(
Sum('playtime')
)['playtime__sum']
cache.set('total_runs', total_runs, timeout=None)
cache.set('total_runtime', total_runtime, timeout=None)
cache.set('total_playtime', total_playtime, timeout=None)
3
Example 34
Project: informer Source File: cache.py
def check_availability(self):
"""
Perform check against default cache configuration
"""
try:
cache.set('foo', 'bar', 30)
cache.get('foo')
except Exception as error:
raise InformerException(
'An error occured when trying access cache: %s.' % error)
else:
return True, 'Your cache system is operational.'
3
Example 35
def test_uncache(self):
criteria = Criteria.objects.create(name='test_crit')
flag = Flag.objects.create(name='test_flag')
conflict = Flag.objects.create(name='nega-test_flag')
flag.conflicts.add(conflict)
criteria.flags.add(flag, conflict)
mock = mox.Mox()
mock.StubOutWithMock(cache, 'set')
cache.set('flag_conflicts:test_flag', None, 5)
mock.StubOutWithMock(utils, 'uncache_criteria')
utils.uncache_criteria(instance=criteria)
mock.ReplayAll()
uncache_flag(instance=flag)
mock.VerifyAll()
mock.UnsetStubs()
3
Example 36
Project: django-rest-framework Source File: test_renderers.py
def test_head_caching(self):
"""
Test caching of HEAD requests
"""
response = self.client.head('/cache')
cache.set('key', response)
cached_response = cache.get('key')
assert isinstance(cached_response, Response)
assert cached_response.content == response.content
assert cached_response.status_code == response.status_code
3
Example 37
@cache_page(60 * 1)
def index(request):
cache.set('my_key', 'hello, world!', 30)
logging.info(cache.get('my_key'))
print cache.get('my_key')
query = Storage.objects.all().order_by('-updated').filter(kind='image')[:5]
threads = Thread.objects.all().order_by('-updated').filter(ref=None)[:5]
#return HttpResponseRedirect('/r')
return render_to_response('index.html',{'photos':query,'threads':threads},context_instance=RequestContext(request))
3
Example 38
Project: django-tracking Source File: listeners.py
def refresh_banned_ips(sender, instance, created=False, **kwargs):
"""Updates the cache of banned IP addresses"""
log.debug('Updating banned IP cache')
cache.set('_tracking_banned_ips',
[b.ip_address for b in BannedIP.objects.all()],
3600)
3
Example 39
Project: django-leonardo Source File: reverse.py
def cycle_app_reverse_cache(*args, **kwargs):
"""Does not really empty the cache; instead it adds a random element to the
cache key generation which guarantees that the cache does not yet contain
values for all newly generated keys"""
value = '%07x' % (SystemRandom().randint(0, 0x10000000))
cache.set(APP_REVERSE_CACHE_GENERATION_KEY, value)
return value
3
Example 40
Project: django-addendum Source File: models.py
def set_cached_snippet(key):
"""
Adds a dictionary of snippet text and translations to the cache.
The default text has the key of an empty string.
{
"": "Hello, humans",
"es": "Hola, humanos",
"en-au": "G'day, humans",
}
"""
text_dict = {
trans.language: trans.text for trans in
SnippetTranslation.objects.filter(snippet_id=key)
}
text_dict.update({'': Snippet.objects.get(key=key).text})
cache.set('snippet:{0}'.format(key), text_dict)
3
Example 41
Project: django-parler Source File: cache.py
def _cache_translation_needs_fallback(instance, language_code, related_name, timeout=DEFAULT_TIMEOUT):
"""
Store the fact that a translation doesn't exist, and the fallback should be used.
"""
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return
tr_model = instance._parler_meta.get_model_by_related_name(related_name)
key = get_translation_cache_key(tr_model, instance.pk, language_code)
cache.set(key, {'__FALLBACK__': True}, timeout=timeout)
3
Example 42
Project: djangae Source File: paginator.py
def _store_marker(query_id, page_number, marker_value):
"""
For a model and query id, stores the marker value for previously
queried page number.
This stores the last item on the page identified by page number,
not the marker that starts the page. i.e. there is a marker for page 1
"""
cache_key = _marker_cache_key(query_id, page_number)
cache.set(cache_key, marker_value, CACHE_TIME)
3
Example 43
def test_get(self):
cache.set('foo', 'bar', 60)
cache.set('moof', 'baz', 1)
simple_cache = SimpleCache()
self.assertEqual(simple_cache.get('foo'), 'bar')
self.assertEqual(simple_cache.get('moof'), 'baz')
self.assertEqual(simple_cache.get(''), None)
3
Example 44
Project: treeio Source File: chat.py
def set_memcached(key, obj, lock=True):
"""
Serialization object and add his in memcached
"""
if lock:
if create_lock(key):
# 60 sec * 60 min * 24 hour * 30 day = 2 592 000 sec
cache.set(key, cPickle.dumps(obj), 2592000)
delete_lock(key)
else:
cache.set(key, cPickle.dumps(obj), 2592000)
3
Example 45
def clear_cache(*args, **kwargs):
"""
Invalidate currently cached messages by starting to use a higher
cache version number for our caching.
Arguments are ignored so we can call this from a signal handler.
"""
from .models import MessageText # avoid circular import
cache_version = _get_cache_version()
cache_version += 1
cache.set(MessageText.CACHE_VERSION_KEY, cache_version)
3
Example 46
def setUp(self):
self.urls = {
'/page1.html': 'key1',
'/page2.html': 'key2',
'/page3.html?foo=bar': 'key3',
'/page3.html?foo=else': 'key4',
}
for key, value in self.urls.items():
cache.set(value, key)
cache.set(REMEMBERED_URLS_KEY, self.urls, 5)
3
Example 47
Project: potatopage Source File: paginator.py
def _put_cursor(self, zero_based_page, cursor):
if not self.object_list.supports_cursors or cursor is None:
return
logging.info("Storing cursor for page: %s" % (zero_based_page))
key = "|".join([self.object_list.cache_key, str(zero_based_page)])
cache.set(key, cursor)
3
Example 48
def get_async_progress(request, *args, **kwargs):
""" Returns the progress as json for use with ajax """
if 'runcode' in kwargs:
runcode = kwargs['runcode']
else:
session_runcode = request.session.get('runcode', None)
if session_runcode is not None:
runcode = session_runcode
runinfo = get_runinfo(runcode)
response = dict(progress=get_progress(runinfo))
cache.set('progress' + runinfo.random, response['progress'])
response = HttpResponse(json.dumps(response),
content_type='application/javascript');
response["Cache-Control"] = "no-cache"
return response
3
Example 49
Project: mezzanine Source File: cache.py
def cache_set(key, value, timeout=None, refreshed=False):
"""
Wrapper for ``cache.set``. Stores the cache entry packed with
the desired cache expiry time. When the entry is retrieved from
cache, the packed expiry time is also checked, and if past,
the stale cache entry is stored again with an expiry that has
``CACHE_SET_DELAY_SECONDS`` added to it. In this case the entry
is not returned, so that a cache miss occurs and the entry
should be set by the caller, but all other callers will still get
the stale entry, so no real cache misses ever occur.
"""
if timeout is None:
timeout = settings.CACHE_MIDDLEWARE_SECONDS
refresh_time = timeout + time()
real_timeout = timeout + settings.CACHE_SET_DELAY_SECONDS
packed = (value, refresh_time, refreshed)
return cache.set(_hashed_key(key), packed, real_timeout)
3
Example 50
def __init__(self, title, request, message_template=None):
self.title = title
self.user_ip = get_real_ip(request)
self.created_at = datetime.now()
if message_template is None:
message_template = ('Possible edit conflict:'
' another user started editing this article at %s')
self.message_template = message_template
cache.set(title, self, WIKI_LOCK_DURATION*60)