本文整理匯總了Python中django.core.cache.cache方法的典型用法代碼示例。如果您正苦於以下問題:Python cache.cache方法的具體用法?Python cache.cache怎麽用?Python cache.cache使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.core.cache
的用法示例。
在下文中一共展示了cache.cache方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: photo_list
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def photo_list(request, course_slug, style='horiz'):
if style not in PHOTO_LIST_STYLES:
raise Http404
user = get_object_or_404(Person, userid=request.user.username)
if not has_photo_agreement(user):
url = reverse('config:photo_agreement') + '?return=' + urllib.parse.quote(request.path)
return ForbiddenResponse(request, mark_safe('You must <a href="%s">confirm the photo usage agreement</a> before seeing student photos.' % (url)))
course = get_object_or_404(CourseOffering, slug=course_slug)
members = Member.objects.filter(offering=course, role="STUD").select_related('person', 'offering')
# fire off a task to fetch the photos and warm the cache
pre_fetch_photos(m.person.emplid for m in members)
context = {'course': course, 'members': members}
return render(request, 'grades/photo_list_%s.html' % (style), context)
示例2: _test_method
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def _test_method(self, method, logging):
mock_logger = MagicMock()
logging.getLogger.return_value = mock_logger
# Patch the parent class of MemorySafePyLibMCCache, then reimport
with patch.object(PyLibMCCache, method) as mock_method:
importlib.reload(backends)
from core.backends import MemorySafePyLibMCCache
mock_method.__name__ = method
mock_method.side_effect = pylibmc.TooBig()
with patch('django.core.cache.cache', MemorySafePyLibMCCache):
from django.core.cache import cache
getattr(cache, method)('key', 1)
logging.getLogger.assert_called_once_with('core.backends')
mock_logger.exception.assert_called_once_with(
"Silenced cache failure at core.backends."
"MemorySafePyLibMCCache.{}()".format(method)
)
logging.getLogger.reset_mock()
mock_logger.exception.reset_mock()
示例3: test_django_cache
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def test_django_cache(self):
try:
from django.conf import settings
settings.configure(CACHE_BACKEND = 'locmem://')
from django.core.cache import cache
except ImportError:
# no Django, so nothing to test
return
congress = Congress(API_KEY, cache)
self.assertEqual(congress.http.cache, cache)
self.assertEqual(congress.members.http.cache, cache)
self.assertEqual(congress.bills.http.cache, cache)
self.assertEqual(congress.votes.http.cache, cache)
try:
bills = congress.bills.introduced('house')
except Exception as e:
self.fail(e)
示例4: django_cache_add_xdist_key_prefix
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def django_cache_add_xdist_key_prefix(request):
skip_if_no_django()
from django.conf import settings
xdist_prefix = getattr(request.config, 'slaveinput', {}).get('slaveid')
if xdist_prefix:
# Put a prefix like gw0_, gw1_ etc on xdist processes
for existing_cache in caches.all():
existing_cache.key_prefix = xdist_prefix + '_' + existing_cache.key_prefix
existing_cache.clear()
logger.info('Set existing cache key prefix to [%s]', existing_cache.key_prefix)
for name, cache_settings in settings.CACHES.items():
cache_settings['KEY_PREFIX'] = xdist_prefix + '_' + cache_settings.get('KEY_PREFIX', '')
logger.info('Set cache key prefix for [%s] cache to [%s]', name, cache_settings['KEY_PREFIX'])
示例5: handle
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def handle(self, sender, signal, **kwargs):
# only add things to the activity stream if there's a user
if kwargs.get("user", None) is None:
return
target = self.getTargetObj(**kwargs)
# invalidate cache for target followers
users = followers(target)
for user in users:
update_activity_stream_for_user.delay(user.username)
update_activity_stream_for_user.delay(kwargs['user'].username, actor=True)
if signal == signals.create:
action.send(kwargs['user'], verb=self.createVerb, action_object=kwargs['instance'], target=target)
if signal == signals.modify:
action.send(kwargs['user'], verb=self.modifyVerb, action_object=kwargs['instance'], target=target)
示例6: memoize
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def memoize(version=1, cache=default_cache):
def decorator(func):
cache_key_base = _get_cache_key_base(func, version)
@functools.wraps(func)
def wrapper(*args, **kwargs):
cache_key = _get_cache_key(cache_key_base, args, kwargs)
result = cache.get(cache_key, default=MISSING)
if result is MISSING:
result = func(*args, **kwargs)
cache.set(cache_key, result)
return result
return wrapper
return decorator
示例7: make_value
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def make_value(self, key, value, tags):
data = {}
tags = [create_tag_cache_key(_) for _ in tags]
# get tags and their cached values (if exists)
tags_dict = self._cache_instance.get_many(tags)
# set new timestamps for missed tags
for tag_key in tags:
if tags_dict.get(tag_key) is None:
# this should be sent to cache as separate key-value
data[tag_key] = get_timestamp()
tags_dict.update(data)
data[key] = {
'value': value,
'tags': tags_dict,
}
return data
示例8: get
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def get(self, key, default=None, **kwargs):
value = self._cache_instance.get(key, default=NOT_FOUND, **kwargs)
# not found in cache
if value is NOT_FOUND:
return default
tags_dict = value.get('tags')
if not tags_dict:
return value
# check if it has valid tags
cached_tags_dict = self._cache_instance.get_many(tags_dict.keys())
# compare dicts
if not compare_dicts(cached_tags_dict, tags_dict):
# cache is invalid - return default value
return default
return value.get('value', default)
示例9: invalidate_cache_by_tags
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def invalidate_cache_by_tags(self, tags=(), *args, **kwargs):
""" Invalidate cache for this method or property by one of provided tags
:type tags: str | list | tuple | callable
"""
if not self.tags:
raise ValueError('Tags were not specified, nothing to invalidate')
def to_set(obj):
return set([obj] if isinstance(obj, six.string_types) else obj)
callable_meta = self.collect_meta(args, kwargs)
all_tags = to_set(self._format(self.tags, callable_meta))
if not tags:
tags = all_tags
else:
tags = to_set(self._format(tags, callable_meta))
if all_tags:
tags &= all_tags
return self.cache_instance.invalidate(tags)
示例10: test_refresh_cache
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def test_refresh_cache(self):
a, b = u'a', u'b'
cache_callable = ordinal_func
self.cache.reset_mock()
result = process_args(a=a, b=b)
self.assertEqual(cache_callable(a=a, b=b), result)
self.cache.assert_called_once_with(result)
self.cache.reset_mock()
# cached version
self.assertEqual(cache_callable(a=a, b=b), result)
self.assertFalse(self.cache.called)
self.cache.reset_mock()
# refresh cache via cache key
cache_callable.refresh_cache(a=a, b=b)
self.cache.assert_called_once_with(result)
self.assertEqual(cache_callable(a=a, b=b), result)
self.cache.assert_called_once_with(result)
self.cache.reset_mock()
# Django-related part
示例11: student_photo
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def student_photo(request, emplid):
# confirm user's photo agreement
user = get_object_or_404(Person, userid=request.user.username)
can_access = False
if Role.objects_fresh.filter(person=user, role__in=['ADVS', 'ADVM']):
can_access = True
else:
if not has_photo_agreement(user):
url = reverse('config:photo_agreement') + '?return=' + urllib.parse.quote(request.path)
return ForbiddenResponse(request, mark_safe('You must <a href="%s">confirm the photo usage agreement</a> before seeing student photos.' % (url)))
# confirm user is an instructor of this student (within the last two years)
# TODO: cache past_semester to save the query?
past_semester = Semester.get_semester(datetime.date.today() - datetime.timedelta(days=730))
student_members = Member.objects.filter(offering__semester__name__gte=past_semester.name,
person__emplid=emplid, role='STUD').select_related('offering')
student_offerings = [m.offering for m in student_members]
instructor_of = Member.objects.filter(person=user, role='INST', offering__in=student_offerings)
can_access = (instructor_of.count() > 0)
if not can_access:
return ForbiddenResponse(request, 'You must be an instructor of this student.')
# get the photo
data, status = photo_for_view(emplid)
# return the photo
response = HttpResponse(data, content_type='image/jpeg')
response.status_code = status
response['Content-Disposition'] = 'inline; filename="%s.jpg"' % (emplid)
response['Cache-Control'] = 'private, max-age=300'
return response
示例12: get_cached_choices
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def get_cached_choices(self):
if not self.cache_config['enabled']:
return None
c = caches(self.cache_config['cache'])
return c.get(self.cache_config['key']%self.field_path)
示例13: set_cached_choices
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def set_cached_choices(self,choices):
if not self.cache_config['enabled']:
return
c = caches(self.cache_config['cache'])
return c.set(self.cache_config['key']%self.field_path,choices)
示例14: get_cached_choices
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def get_cached_choices(self):
if not self.cache_config['enabled']:
return None
c = caches(self.cache_config['cache'])
return c.get(self.cache_config['key'] % self.field_path)
示例15: set_cached_choices
# 需要導入模塊: from django.core import cache [as 別名]
# 或者: from django.core.cache import cache [as 別名]
def set_cached_choices(self, choices):
if not self.cache_config['enabled']:
return
c = caches(self.cache_config['cache'])
return c.set(self.cache_config['key'] % self.field_path, choices)