Python django.core.cache.caches() Examples

The following are 30 code examples for showing how to use django.core.cache.caches(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.cache , or try the search function .

Example 1
Project: Servo   Author: fpsw   File: parts.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 2
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 3
Project: django-cachalot   Author: noripyt   File: benchmark.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: django-cachalot   Author: noripyt   File: benchmark.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Project: bioforum   Author: reBiocoder   File: cache.py    License: MIT License 6 votes vote down vote up
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
Project: django-aws-template   Author: dkarchmer   File: middleware.py    License: MIT License 6 votes vote down vote up
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 7
Project: django-userlog   Author: aaugustin   File: util.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 8
Project: graphene-django-extras   Author: eamigo86   File: views.py    License: MIT License 6 votes vote down vote up
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 9
Project: ishare   Author: jeeyshe   File: views.py    License: MIT License 6 votes vote down vote up
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 10
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: cache.py    License: MIT License 6 votes vote down vote up
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 11
Project: django-healthchecks   Author: mvantellingen   File: test_contrib.py    License: MIT License 5 votes vote down vote up
def test_check_cache_default():
    cache.caches = cache.CacheHandler()
    assert contrib.check_cache_default() 
Example 12
Project: django-healthchecks   Author: mvantellingen   File: test_contrib.py    License: MIT License 5 votes vote down vote up
def test_check_cache_default_down(settings):
    """Check if the application can connect to the default cached and
    read/write some dummy data.

    """
    cache.caches = cache.CacheHandler()
    settings.CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
    assert not contrib.check_cache_default() 
Example 13
Project: coursys   Author: sfu-fas   File: rest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CacheMixin, self).__init__(*args, **kwargs)

        # borrowed from FetchFromCacheMiddleware
        self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
        self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
        self.cache = caches[self.cache_alias] 
Example 14
Project: coursys   Author: sfu-fas   File: rest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default_response_headers(self):
        # shouldn't be necessary since we're setting "cache-control: private" and delivering by HTTPS, but be sure
        # there's no cross-contamination in caches
        h = super(CacheMixin, self).default_response_headers
        h['Vary'] = 'Accept, Authorization, Cookie'
        return h 
Example 15
Project: StormOnline   Author: stormsha   File: filters.py    License: Apache License 2.0 5 votes vote down vote up
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 16
Project: StormOnline   Author: stormsha   File: filters.py    License: Apache License 2.0 5 votes vote down vote up
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 17
Project: django-defender   Author: jazzband   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def get_redis_connection():
    """ Get the redis connection if not using mock """
    if config.MOCK_REDIS:  # pragma: no cover
        import mockredis

        return mockredis.mock_strict_redis_client()  # pragma: no cover
    elif config.DEFENDER_REDIS_NAME:  # pragma: no cover
        try:
            cache = caches[config.DEFENDER_REDIS_NAME]
        except InvalidCacheBackendError:
            raise KeyError(INVALID_CACHE_ERROR_MSG.format(config.DEFENDER_REDIS_NAME))
        # every redis backend implement it own way to get the low level client
        try:
            # redis_cache.RedisCache case (django-redis-cache package)
            return cache.get_master_client()
        except AttributeError:
            # django_redis.cache.RedisCache case (django-redis package)
            return cache.client.get_client(True)
    else:  # pragma: no cover
        redis_config = parse_redis_url(
            config.DEFENDER_REDIS_URL, config.DEFENDER_REDIS_PASSWORD_QUOTE)
        return redis.StrictRedis(
            host=redis_config.get("HOST"),
            port=redis_config.get("PORT"),
            db=redis_config.get("DB"),
            password=redis_config.get("PASSWORD"),
            ssl=redis_config.get("SSL"),
        ) 
Example 18
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        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] 
Example 19
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
        self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
        self.cache = caches[self.cache_alias] 
Example 20
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, cache_timeout=None, **kwargs):
        # We need to differentiate between "provided, but using default value",
        # and "not provided". If the value is provided using a default, then
        # we fall back to system defaults. If it is not provided at all,
        # we need to use middleware defaults.

        try:
            key_prefix = kwargs['key_prefix']
            if key_prefix is None:
                key_prefix = ''
        except KeyError:
            key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
        self.key_prefix = key_prefix

        try:
            cache_alias = kwargs['cache_alias']
            if cache_alias is None:
                cache_alias = DEFAULT_CACHE_ALIAS
        except KeyError:
            cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
        self.cache_alias = cache_alias

        if cache_timeout is None:
            cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
        self.cache_timeout = cache_timeout
        self.cache = caches[self.cache_alias] 
Example 21
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        try:
            expire_time = self.expire_time_var.resolve(context)
        except VariableDoesNotExist:
            raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var)
        try:
            expire_time = int(expire_time)
        except (ValueError, TypeError):
            raise TemplateSyntaxError('"cache" tag got a non-integer timeout value: %r' % expire_time)
        if self.cache_name:
            try:
                cache_name = self.cache_name.resolve(context)
            except VariableDoesNotExist:
                raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.cache_name.var)
            try:
                fragment_cache = caches[cache_name]
            except InvalidCacheBackendError:
                raise TemplateSyntaxError('Invalid cache name specified for cache tag: %r' % cache_name)
        else:
            try:
                fragment_cache = caches['template_fragments']
            except InvalidCacheBackendError:
                fragment_cache = caches['default']

        vary_on = [var.resolve(context) for var in self.vary_on]
        cache_key = make_template_fragment_key(self.fragment_name, vary_on)
        value = fragment_cache.get(cache_key)
        if value is None:
            value = self.nodelist.render(context)
            fragment_cache.set(cache_key, value, expire_time)
        return value 
Example 22
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, session_key=None):
        self._cache = caches[settings.SESSION_CACHE_ALIAS]
        super(SessionStore, self).__init__(session_key) 
Example 23
Project: GTDWeb   Author: lanbing510   File: cached_db.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, session_key=None):
        self._cache = caches[settings.SESSION_CACHE_ALIAS]
        super(SessionStore, self).__init__(session_key) 
Example 24
Project: GTDWeb   Author: lanbing510   File: createcachetable.py    License: GNU General Public License v2.0 5 votes vote down vote up
def handle(self, *tablenames, **options):
        db = options.get('database')
        self.verbosity = int(options.get('verbosity'))
        if len(tablenames):
            # Legacy behavior, tablename specified as argument
            for tablename in tablenames:
                self.create_table(db, tablename)
        else:
            for cache_alias in settings.CACHES:
                cache = caches[cache_alias]
                if isinstance(cache, BaseDatabaseCache):
                    self.create_table(db, cache._table) 
Example 25
Project: koku   Author: project-koku   File: tests_cache.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """Set up cache tests."""
        super().setUp()

        self.cache = caches["default"]
        self.cache_key_prefix = random.choice(CACHE_PREFIXES) 
Example 26
Project: koku   Author: project-koku   File: cache.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def invalidate_view_cache_for_tenant_and_cache_key(schema_name, cache_key_prefix=None):
    """Invalidate our view cache for a specific tenant and source type.

    If cache_key_prefix is None, all views will be invalidated.
    """
    cache = caches["default"]
    if isinstance(cache, RedisCache):
        cache = Redis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_DB)
        all_keys = cache.keys("*")
        all_keys = [key.decode("utf-8") for key in all_keys]
    elif isinstance(cache, LocMemCache):
        all_keys = list(locmem._caches.get(settings.TEST_CACHE_LOCATION).keys())
        all_keys = [key.split(":", 2)[-1] for key in all_keys]
    else:
        msg = "Using an unsupported caching backend!"
        raise KokuCacheError(msg)

    all_keys = all_keys if all_keys is not None else []

    if cache_key_prefix:
        keys_to_invalidate = [key for key in all_keys if (schema_name in key and cache_key_prefix in key)]
    else:
        # Invalidate all cached views for the tenant
        keys_to_invalidate = [key for key in all_keys if schema_name in key]

    for key in keys_to_invalidate:
        cache.delete(key)

    msg = f"Invalidated request cache for\n\ttenant: {schema_name}\n\tcache_key_prefix: {cache_key_prefix}"
    LOG.info(msg) 
Example 27
Project: koku   Author: project-koku   File: tests_middleware.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_process_non_admin(self, get_access_mock):
        """Test case for process_request as a non-admin user."""
        mock_access = {
            "aws.account": {"read": ["999999999999"]},
            "openshift.cluster": {"read": ["999999999999"]},
            "openshift.node": {"read": ["999999999999"]},
            "openshift.project": {"read": ["999999999999"]},
            "provider": {"read": ["999999999999"], "write": []},
            "rate": {"read": ["999999999999"], "write": []},
        }
        get_access_mock.return_value = mock_access

        user_data = self._create_user_data()
        customer = self._create_customer_data()
        request_context = self._create_request_context(
            customer, user_data, create_customer=True, create_tenant=True, is_admin=False
        )
        mock_request = request_context["request"]
        mock_request.path = "/api/v1/tags/aws/"
        mock_request.META["QUERY_STRING"] = ""

        middleware = IdentityHeaderMiddleware()
        middleware.process_request(mock_request)

        user_uuid = mock_request.user.uuid
        cache = caches["rbac"]
        self.assertEqual(cache.get(user_uuid), mock_access)

        middleware.process_request(mock_request)
        cache = caches["rbac"]
        self.assertEqual(cache.get(user_uuid), mock_access) 
Example 28
Project: django-prometheus   Author: korfuri   File: test_caches.py    License: Apache License 2.0 5 votes vote down vote up
def testCounters(self):
        supported_caches = ["memcached", "filebased", "locmem", "redis"]

        # Note: those tests require a memcached server running
        for supported_cache in supported_caches:
            tested_cache = caches[supported_cache]

            total_before = (
                self.getMetric("django_cache_get_total", backend=supported_cache) or 0
            )
            hit_before = (
                self.getMetric("django_cache_get_hits_total", backend=supported_cache)
                or 0
            )
            miss_before = (
                self.getMetric("django_cache_get_misses_total", backend=supported_cache)
                or 0
            )

            tested_cache.set("foo1", "bar")
            tested_cache.get("foo1")
            tested_cache.get("foo1")
            tested_cache.get("foofoo")

            result = tested_cache.get("foofoo", default="default")

            assert result == "default"

            self.assertMetricEquals(
                total_before + 4, "django_cache_get_total", backend=supported_cache
            )
            self.assertMetricEquals(
                hit_before + 2, "django_cache_get_hits_total", backend=supported_cache
            )
            self.assertMetricEquals(
                miss_before + 2,
                "django_cache_get_misses_total",
                backend=supported_cache,
            ) 
Example 29
Project: django-prometheus   Author: korfuri   File: test_caches.py    License: Apache License 2.0 5 votes vote down vote up
def test_cache_version_support(self):
        supported_caches = ["memcached", "filebased", "locmem", "redis"]

        # Note: those tests require a memcached server running
        for supported_cache in supported_caches:
            tested_cache = caches[supported_cache]

            tested_cache.set("foo1", "bar v.1", version=1)
            tested_cache.set("foo1", "bar v.2", version=2)

            assert "bar v.1" == tested_cache.get("foo1", version=1)
            assert "bar v.2" == tested_cache.get("foo1", version=2) 
Example 30
Project: telemetry-analysis-service   Author: mozilla   File: cache.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def get_backend(self):
        return caches["default"]