本文整理汇总了Python中django.core.cache.cache.get_or_set方法的典型用法代码示例。如果您正苦于以下问题:Python cache.get_or_set方法的具体用法?Python cache.get_or_set怎么用?Python cache.get_or_set使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.cache.cache
的用法示例。
在下文中一共展示了cache.get_or_set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: user_board_listing
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def user_board_listing(request, account_id):
"""Return a paginated board listing view for account with account_id."""
metric_timeout_seconds = 60 * 2
queries = {
# default to boards contributed to
None: lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
'created': lambda x: ('created', user_boards_created(x, viewing_user=request.user)),
'evaluated': lambda x: ('evaluated', user_boards_evaluated(x, viewing_user=request.user)),
'contribute': lambda x: ('contributed to', user_boards_contributed(x, viewing_user=request.user)),
}
user = get_object_or_404(User, pk=account_id)
query = request.GET.get('query')
verb, board_list = queries.get(query, queries[None])(user)
desc = _('List of intelligence boards user {username} has {verb}').format(username=user.username, verb=verb)
context = {
'user': user,
'boards': make_paginator(request, board_list),
'contributors': cache.get_or_set('contributor_count', generate_contributor_count(), metric_timeout_seconds),
'evaluators': cache.get_or_set('evaluator_count', generate_evaluator_count(), metric_timeout_seconds),
'meta_description': desc,
'verb': verb
}
return render(request, 'boards/user_boards.html', context)
示例2: _load_user_dn
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def _load_user_dn(self):
"""
Populates self._user_dn with the distinguished name of our user.
This will either construct the DN from a template in
AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it.
If we have to search, we'll cache the DN.
"""
if self._using_simple_bind_mode():
self._user_dn = self._construct_simple_user_dn()
else:
if self.settings.CACHE_TIMEOUT > 0:
cache_key = valid_cache_key(
"django_auth_ldap.user_dn.{}".format(self._username)
)
self._user_dn = cache.get_or_set(
cache_key, self._search_for_user_dn, self.settings.CACHE_TIMEOUT
)
else:
self._user_dn = self._search_for_user_dn()
示例3: test_get_or_set_version
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def test_get_or_set_version(self):
msg_re = r"get_or_set\(\) missing 1 required positional argument: 'default'"
cache.get_or_set("brian", 1979, version=2)
with pytest.raises(TypeError, match=msg_re):
cache.get_or_set("brian")
with pytest.raises(TypeError, match=msg_re):
cache.get_or_set("brian", version=1)
assert cache.get("brian", version=1) is None
assert cache.get_or_set("brian", 42, version=1) == 42
assert cache.get_or_set("brian", 1979, version=2) == 1979
assert cache.get("brian", version=3) is None
# Modified Django tests
示例4: category_view
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def category_view(request, slug):
# If getting by slug fails, also try to get it by name.
try:
category = BuyersGuideProductCategory.objects.get(slug=slug)
except ObjectDoesNotExist:
category = get_object_or_404(BuyersGuideProductCategory, name__iexact=slug)
key = f'products_category__{slug.replace(" ", "_")}'
products = cache.get_or_set(
key,
lambda: [p.to_dict() for p in Product.objects.filter(product_category__in=[category]).distinct()],
86400
)
products = filter_draft_products(request, products)
return render(request, 'category_page.html', {
'categories': BuyersGuideProductCategory.objects.all(),
'category': category,
'products': products,
'mediaUrl': MEDIA_URL,
})
示例5: about
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def about(request):
"""Information about the current site, its goals, and what content is loaded"""
# Provider counts
providers = cache.get_or_set(CACHE_STATS_NAME, [], CACHE_STATS_DURATION)
if not providers:
for provider in sorted(settings.PROVIDERS.keys()):
s = Search()
q = Q('term', provider=provider)
s = s.query(q)
response = s.execute()
if response.hits.total > 0:
data = settings.PROVIDERS[provider]
total = intcomma(response.hits.total)
data.update({'hits': total})
providers.append(data)
# All results
s = Search()
response = s.execute()
total = intcomma(response.hits.total)
providers.append({'display_name': 'Total', 'hits': total})
cache.set(CACHE_STATS_NAME, providers)
return render(request, "about.html", {'providers': providers})
示例6: board_listing
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def board_listing(request):
"""Return a paginated board listing view showing all boards and their popularity."""
board_list = Board.objects.user_readable(request.user).order_by('-pub_date')
metric_timeout_seconds = 60 * 2
desc = _('List of intelligence boards on {name} and summary information').format(name=get_current_site(request).name) # nopep8
context = {
'boards': make_paginator(request, board_list),
'contributors': cache.get_or_set('contributor_count', generate_contributor_count(), metric_timeout_seconds),
'evaluators': cache.get_or_set('evaluator_count', generate_evaluator_count(), metric_timeout_seconds),
'meta_description': desc,
}
return render(request, 'boards/boards.html', context)
示例7: _config
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def _config(self):
key = utils.make_template_fragment_key("{}.{}.{}".format(
self.request.user.id, self.model_name, 'list'))
data = cache.get_or_set(key,
get_user_config(self.request.user, 'list', self.model), 180)
return data
示例8: list
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def list(self, request):
key = 'desecapi.views.serials'
serials = cache.get(key)
if serials is None:
serials = get_serials()
cache.get_or_set(key, serials, timeout=15)
return Response(serials)
示例9: cached_request
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def cached_request(self, method, token, cache_prefix):
token_hash = hashlib.sha256(force_bytes(token)).hexdigest()
func = functools.partial(method, token, None, None)
return cache.get_or_set(
f"{cache_prefix}.{token_hash}",
func,
timeout=settings.OIDC_BEARER_TOKEN_REVALIDATION_TIME,
)
示例10: get_data
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def get_data(self, **kwargs): # pylint: disable=arguments-differ
return cache.get_or_set(API_TIMESTAMP_KEY, time.time, None)
示例11: index
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def index(request):
page = int(request.GET.get('p', 0))
stories = cache.get_or_set("news-index-%s"%(page), lambda: list(_front_page(page=page)), timeout=TIMEOUT_MEDIUM) # one minute
if len(stories) < 1 and page != 0:
back = _one_page_back(request)
if back:
return back
return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})
示例12: show
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def show(request):
page = int(request.GET.get('p', 0))
stories = cache.get_or_set("news-show-%s"%(page), lambda: list(_front_page(page=page, add_filter={'is_show': True})), timeout=TIMEOUT_MEDIUM) # one minute
if len(stories) < 1 and page != 0:
back = _one_page_back(request)
if back:
return back
return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})
示例13: ask
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def ask(request):
page = int(request.GET.get('p', 0))
stories = lambda: list(_front_page(page=page, add_filter={'is_ask': True}))
stories = cache.get_or_set("news-ask-%s"%(page), stories, timeout=TIMEOUT_MEDIUM) # one minute
if len(stories) < 1 and page != 0:
back = _one_page_back(request)
if back:
return back
return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})
示例14: newest
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def newest(request): # Done
page = int(request.GET.get('p', 0))
add_filter = {}
add_q = []
if 'submitted_by' in request.GET.keys():
try:
submitted_by = CustomUser.objects.get_by_natural_key(request.GET['submitted_by'])
add_filter['user'] = submitted_by
except CustomUser.DoesNotExist:
raise Http404()
if 'upvoted_by' in request.GET.keys():
try:
assert request.user.is_authenticated
assert request.user.username == request.GET['upvoted_by']
except AssertionError:
return HttpResponseForbidden()
add_filter['pk__in'] = Vote.objects.filter(vote=1, user=request.user).values('item')
add_q.append(~Q(user=request.user))
if 'site' in request.GET.keys():
add_filter['domain'] = request.GET['site']
stories = lambda: list(_newest(page=page, add_filter=add_filter, add_q=add_q))
stories = cache.get_or_set("news-newest-%s"%(page), stories, timeout=TIMEOUT_SHORT) # two seconds
if len(stories) < 1 and page != 0:
back = _one_page_back(request)
if back:
return back
return render(request, 'news/index.html', {'stories': stories, 'hide_text':True, 'page': page, 'rank_start': page*settings.PAGING_SIZE})
示例15: observer_evaluate
# 需要导入模块: from django.core.cache import cache [as 别名]
# 或者: from django.core.cache.cache import get_or_set [as 别名]
def observer_evaluate(self, message):
"""Execute observer evaluation on the worker or throttle."""
observer_id = message['observer']
throttle_rate = get_queryobserver_settings()['throttle_rate']
if throttle_rate <= 0:
await self._evaluate(observer_id)
return
cache_key = throttle_cache_key(observer_id)
try:
count = cache.incr(cache_key)
# Ignore if delayed observer already scheduled.
if count == 2:
await self.channel_layer.send(
CHANNEL_MAIN,
{
'type': TYPE_POLL,
'observer': observer_id,
'interval': throttle_rate,
},
)
except ValueError:
count = cache.get_or_set(cache_key, default=1, timeout=throttle_rate)
# Ignore if cache was set and increased in another thread.
if count == 1:
await self._evaluate(observer_id)