Python django.core.cache.caches() Examples
The following are 30
code examples of django.core.cache.caches().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.core.cache
, or try the search function
.
Example #1
Source File: util.py From django-userlog with BSD 3-Clause "New" or "Revised" License | 6 votes |
def get_redis_client(): global _client if _client is not None: return _client try: cache = caches['userlog'] except KeyError: raise ImproperlyConfigured("No 'userlog' cache found in CACHES.") try: try: _client = cache.client # django-redis except AttributeError: _client = cache.get_master_client() # django-redis-cache assert isinstance(_client, redis.StrictRedis) except (AssertionError, AttributeError): raise ImproperlyConfigured("'userlog' cache doesn't use Redis.") return _client
Example #2
Source File: views.py From ishare with MIT License | 6 votes |
def get(self, request, pk): # 获取文章详情 obj = self.get_obj(pk) if not obj: raise Http404() ctx = { 'art': obj, 'tags': ContextUtil.random_tags(), 'cnxh': self.get_cnxh(obj), 'others': self.get_others(obj), 'next': self.get_next(obj), 'prev': self.get_prev(obj), 'liked': self.get_art_like_status(pk), } # 更新阅读次数 obj.read += 1 obj.save(update_fields=('read',)) obj.like += caches['four'].get('like_{}'.format(pk), 0) return render(request, 'db/detail.html', ctx)
Example #3
Source File: benchmark.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def benchmark(self, query_str, to_list=True, num_queries=1): # Clears the cache before a single benchmark to ensure the same # conditions across single benchmarks. caches[settings.CACHALOT_CACHE].clear() self.query_name = query_str query_str = 'Test.objects.using(using)' + query_str if to_list: query_str = 'list(%s)' % query_str self.query_function = eval('lambda using: ' + query_str) with override_settings(CACHALOT_ENABLED=False): self.bench_once(CONTEXTS[0], num_queries) self.bench_once(CONTEXTS[1], num_queries, invalidate_before=True) self.bench_once(CONTEXTS[2], 0)
Example #4
Source File: benchmark.py From django-cachalot with BSD 3-Clause "New" or "Revised" License | 6 votes |
def run(self): for db_alias in settings.DATABASES: self.db_alias = db_alias self.db_vendor = connections[self.db_alias].vendor print('Benchmarking %s…' % self.db_vendor) for cache_alias in settings.CACHES: cache = caches[cache_alias] self.cache_name = cache.__class__.__name__[:-5].lower() with override_settings(CACHALOT_CACHE=cache_alias): self.execute_benchmark() self.df = pd.DataFrame.from_records(self.data) if not os.path.exists(RESULTS_PATH): os.mkdir(RESULTS_PATH) self.df.to_csv(os.path.join(RESULTS_PATH, 'data.csv')) self.xlim = (0, self.df['time'].max() * 1.01) self.output('db') self.output('cache')
Example #5
Source File: cache.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that the page needs to be rebuilt. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None
Example #6
Source File: views.py From graphene-django-extras with MIT License | 6 votes |
def dispatch(self, request, *args, **kwargs): """ Fetches queried data from graphql and returns cached & hashed key. """ if not graphql_api_settings.CACHE_ACTIVE: return self.super_call(request, *args, **kwargs) cache = caches["default"] operation_ast = self.get_operation_ast(request) if operation_ast and operation_ast.operation == "mutation": cache.clear() return self.super_call(request, *args, **kwargs) cache_key = "_graplql_{}".format(self.fetch_cache_key(request)) response = cache.get(cache_key) if not response: response = self.super_call(request, *args, **kwargs) # cache key and value cache.set(cache_key, response, timeout=graphql_api_settings.CACHE_TIMEOUT) return response
Example #7
Source File: cache.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Returns a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there is no headerlist stored, the page needs to be rebuilt, so this function returns None. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key, None) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None
Example #8
Source File: cache.py From bioforum with MIT License | 6 votes |
def get_cache_key(request, key_prefix=None, method='GET', cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that the page needs to be rebuilt. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None
Example #9
Source File: middleware.py From django-aws-template with MIT License | 6 votes |
def get_cached_user(request): if not hasattr(request, '_cached_user'): try: key = CACHE_KEY.format(request.session[SESSION_KEY]) cache = caches['default'] user = cache.get(key) except KeyError: user = AnonymousUser() if user is None: user = get_user(request) cache = caches['default'] # 8 hours cache.set(key, user, 28800) logger.debug('No User Cache. Setting now: {0}, {1}'.format(key, user.username)) request._cached_user = user return request._cached_user
Example #10
Source File: parts.py From Servo with BSD 2-Clause "Simplified" License | 6 votes |
def get_remote_symptom_codes(group): """ Remote lookup for symptom codes """ symptoms = {} cache = caches['comptia'] # First, try to load from global cache (updated every 24h) data = cache.get('codes') or {} if not data: # ... then try to fetch from GSX GsxAccount.fallback() data = gsxws.comptia.fetch() cache.set('codes', data) for k, v in data.get(group): symptoms[k] = v return symptoms
Example #11
Source File: my_middlewares.py From ishare with MIT License | 5 votes |
def after_make_response(self, request): if request.META.get('PATH_INFO', '-').startswith('/x/'): cache = caches['four'] # 总访问记录: 临时存储在redis, 由celery每小时同步到mysql库中 total_cnt = cache.get('total', 0) cache.set('total', total_cnt + 1, 60 * 60 + 60) # 此处设定时间只要大于1h即可, 同步时会重置时间 # 今日访问记录: 使用redis进行高速缓存 today_cnt = cache.get(today_key(), 0) cache.set(today_key(), today_cnt + 1, 60 * 60 * 24 + 60)
Example #12
Source File: cache.py From python with Apache License 2.0 | 5 votes |
def __init__(self, get_response=None): self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS self.cache = caches[self.cache_alias] self.get_response = get_response
Example #13
Source File: tests_utils_ratelimit.py From Spirit with MIT License | 5 votes |
def test_rate_limit_pruned_too_frequently(self): """ Should not limit when the cache\ is pruned too frequently """ req = RequestFactory().post('/') setup_request_factory_messages(req) req.user = User() req.user.pk = 1 @ratelimit(rate='1/m') def one(request): return request.is_limited() foo_cache = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache' }, 'foo': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'foo', 'TIMEOUT': 0 # Faking cache pruned too frequently }} with override_settings(CACHES=foo_cache, ST_RATELIMIT_CACHE='foo'): with warnings.catch_warnings(record=True): # Ignore warnings caches['foo'].clear() self.assertFalse(one(req)) self.assertFalse(one(req))
Example #14
Source File: ratelimit.py From Spirit with MIT License | 5 votes |
def _incr(self, key): cache = caches[settings.ST_RATELIMIT_CACHE] cache.add(key, 0) try: # This resets the timeout to # default, see Django ticket #26619 return cache.incr(key) except ValueError: # Key does not exists # The cache is being # pruned too frequently return 1
Example #15
Source File: ratelimit.py From Spirit with MIT License | 5 votes |
def _get_cache_values(self): return (caches[settings.ST_RATELIMIT_CACHE] .get_many(self.cache_keys))
Example #16
Source File: leonardo_tags.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _render_content(content, **kwargs): # Track current render level and abort if we nest too deep. Avoids # crashing in recursive page contents (eg. a page list that contains # itself or similar). request = kwargs.get('request') if request is not None: level = getattr(request, 'feincms_render_level', 0) if level > 10: logging.getLogger('feincms').error( 'Refusing to render %r, render level is already %s' % ( content, level)) return setattr(request, 'feincms_render_level', level + 1) if request is not None: level = getattr(request, 'feincms_render_level', 1) setattr(request, 'feincms_render_level', max(level - 1, 0)) cache = caches['default'] if not request.frontend_editing and content.is_cached(request): value = cache.get(content.cache_key) if value is None: value = content.render(**kwargs) cache.set(content.cache_key, value, content.widget_cache_timeout) return value return content.render(**kwargs)
Example #17
Source File: widget.py From django-leonardo with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cache(self): '''default cache''' return caches['default']
Example #18
Source File: tests_utils_ratelimit.py From Spirit with MIT License | 5 votes |
def test_rate_limit_hash_key(self): """ Keys should be stored as hashes """ req = RequestFactory().post('/') req.user = User() req.user.pk = 1 rl = RateLimit(req, 'func_name') rl.incr() self.assertEqual( len(rl.cache_keys[0]), len(settings.ST_RATELIMIT_CACHE_PREFIX) + 1 + 40) # prefix:sha1_hash rl_cache = caches[settings.ST_RATELIMIT_CACHE] self.assertIsNotNone(rl_cache.get(rl.cache_keys[0]))
Example #19
Source File: cache.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
def __init__(self, get_response=None): self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS self.cache = caches[self.cache_alias] self.get_response = get_response
Example #20
Source File: cache.py From pylti1.3 with MIT License | 5 votes |
def __init__(self, cache_name='default', **kwargs): self._cache = caches[cache_name] super(DjangoCacheDataStorage, self).__init__(cache_name, **kwargs)
Example #21
Source File: filters.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
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)
Example #22
Source File: cron.py From ishare with MIT License | 5 votes |
def update_visit_count(*args, **kwargs): """ 每小时从redis更新网站总浏览量到mysql """ logger.info("Start update visit count") cache = caches['four'] obj, is_created = Expand.objects.get_or_create(key='VISIT_CNT', defaults={'key': 'VISIT_CNT', 'value': '1'}) if not is_created: real = cache.get('total', 0) obj.value = str(int(obj.value) + real) obj.save(update_fields=('value',)) cache.set('total', 0, 60 * 60 + 60) logger.info("更新网站浏览量完成")
Example #23
Source File: mathoid.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, type): self.type = type self.mathoid_url = settings.MATHOID_URL self.cache = HashFileCache(settings.MATHOID_CACHE_ROOT, settings.MATHOID_CACHE_URL, settings.MATHOID_GZIP) mml_cache = settings.MATHOID_MML_CACHE self.mml_cache = mml_cache and caches[mml_cache] self.css_cache = caches[settings.MATHOID_CSS_CACHE] self.mml_cache_ttl = settings.MATHOID_MML_CACHE_TTL
Example #24
Source File: cache.py From zing with GNU General Public License v3.0 | 5 votes |
def get_cache(cache=None): """Return ``cache`` or the 'default' cache if ``cache`` is not specified or ``cache`` is not configured. :param cache: The name of the requested cache. """ try: # Check for proper Redis persistent backends # FIXME: this logic needs to be a system sanity check if ( not settings.DEBUG and cache in PERSISTENT_STORES and ( cache not in settings.CACHES or "RedisCache" not in settings.CACHES[cache]["BACKEND"] or settings.CACHES[cache].get("TIMEOUT", "") is not None ) ): raise ImproperlyConfigured( "Pootle requires a Redis-backed caching backend for %r " "with `TIMEOUT: None`. Please review your settings." % cache ) return caches[cache] except InvalidCacheBackendError: return default_cache
Example #25
Source File: texoid.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self): self.cache = HashFileCache(settings.TEXOID_CACHE_ROOT, settings.TEXOID_CACHE_URL, settings.TEXOID_GZIP) self.meta_cache = caches[settings.TEXOID_META_CACHE] self.meta_cache_ttl = settings.TEXOID_META_CACHE_TTL
Example #26
Source File: filters.py From django_OA with GNU General Public License v3.0 | 5 votes |
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)
Example #27
Source File: filters.py From django_OA with GNU General Public License v3.0 | 5 votes |
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)
Example #28
Source File: filters.py From myblog with GNU Affero General Public License v3.0 | 5 votes |
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)
Example #29
Source File: filters.py From CTF_AWD_Platform with MIT License | 5 votes |
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)
Example #30
Source File: filters.py From CTF_AWD_Platform with MIT License | 5 votes |
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)