當前位置: 首頁>>代碼示例>>Python>>正文


Python settings.CACHES屬性代碼示例

本文整理匯總了Python中django.conf.settings.CACHES屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.CACHES屬性的具體用法?Python settings.CACHES怎麽用?Python settings.CACHES使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在django.conf.settings的用法示例。


在下文中一共展示了settings.CACHES屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: settings_info

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def settings_info():
    info = []
    info.append(('Deploy mode', settings.DEPLOY_MODE))
    info.append(('Database engine', settings.DATABASES['default']['ENGINE']))
    info.append(('Authentication Backends', settings.AUTHENTICATION_BACKENDS))
    info.append(('Cache backend', settings.CACHES['default']['BACKEND']))
    info.append(('Haystack engine', settings.HAYSTACK_CONNECTIONS['default']['ENGINE']))
    info.append(('Email backend', settings.EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_EMAIL') and settings.CELERY_EMAIL:
        info.append(('Celery email backend', settings.CELERY_EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_BROKER_URL'):
        info.append(('Celery broker', settings.CELERY_BROKER_URL.split(':')[0]))

    DATABASES = copy.deepcopy(settings.DATABASES)
    for d in DATABASES:
        if 'PASSWORD' in DATABASES[d]:
            DATABASES[d]['PASSWORD'] = '*****'
    info.append(('DATABASES',  mark_safe('<pre>'+escape(pprint.pformat(DATABASES))+'</pre>')))

    return info 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:22,代碼來源:panel.py

示例2: _create_cache

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def _create_cache(backend, **kwargs):
    try:
        # Try to get the CACHES entry for the given backend name first
        try:
            conf = settings.CACHES[backend]
        except KeyError:
            try:
                # Trying to import the given backend, in case it's a dotted path
                import_string(backend)
            except ImportError as e:
                raise InvalidCacheBackendError("Could not find backend '%s': %s" % (
                    backend, e))
            location = kwargs.pop('LOCATION', '')
            params = kwargs
        else:
            params = conf.copy()
            params.update(kwargs)
            backend = params.pop('BACKEND')
            location = params.pop('LOCATION', '')
        backend_cls = import_string(backend)
    except ImportError as e:
        raise InvalidCacheBackendError(
            "Could not find backend '%s': %s" % (backend, e))
    return backend_cls(location, params) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:26,代碼來源:__init__.py

示例3: __getitem__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def __getitem__(self, alias):
        try:
            return self._caches.caches[alias]
        except AttributeError:
            self._caches.caches = {}
        except KeyError:
            pass

        if alias not in settings.CACHES:
            raise InvalidCacheBackendError(
                "Could not find config for '%s' in settings.CACHES" % alias
            )

        cache = _create_cache(alias)
        self._caches.caches[alias] = cache
        return cache 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:18,代碼來源:__init__.py

示例4: run

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
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') 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:21,代碼來源:benchmark.py

示例5: get_redis_client

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
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 
開發者ID:aaugustin,項目名稱:django-userlog,代碼行數:23,代碼來源:util.py

示例6: get_userlog_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def get_userlog_settings():
    global _settings

    if _settings is not None:
        return _settings

    def get_setting(name, default):
        return getattr(settings, 'USERLOG_' + name, default)

    # Coerce values into expected types in order to detect invalid settings.
    _settings = UserLogSettings(
        # Hardcode the default timeout because it isn't exposed by Django.
        timeout=int(settings.CACHES['userlog'].get('TIMEOUT', 300)),
        max_size=int(get_setting('MAX_SIZE', 25)),
        publish=bool(get_setting('PUBLISH', True)),
        ignore_urls=[re.compile(pattern)
                     for pattern in get_setting('IGNORE_URLS', [])],
        websocket_address=str(get_setting('WEBSOCKET_ADDRESS',
                                          'ws://localhost:8080/')),
    )

    return _settings 
開發者ID:aaugustin,項目名稱:django-userlog,代碼行數:24,代碼來源:util.py

示例7: parse_backend_conf

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def parse_backend_conf(backend, **kwargs):
    """
    Helper function to parse the backend configuration
    that doesn't use the URI notation.
    """
    # Try to get the CACHES entry for the given backend name first
    conf = settings.CACHES.get(backend, None)
    if conf is not None:
        args = conf.copy()
        args.update(kwargs)
        backend = args.pop('BACKEND')
        location = args.pop('LOCATION', '')
        return backend, location, args
    else:
        try:
            # Trying to import the given backend, in case it's a dotted path
            mod_path, cls_name = backend.rsplit('.', 1)
            mod = importlib.import_module(mod_path)
            backend_cls = getattr(mod, cls_name)
        except (AttributeError, ImportError, ValueError):
            raise InvalidCacheBackendError("Could not find backend '%s'" % backend)
        location = kwargs.pop('LOCATION', '')
        return backend, location, kwargs 
開發者ID:blackye,項目名稱:luscan-devel,代碼行數:25,代碼來源:__init__.py

示例8: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def handle(self, *args, **options):
        verbosity = options.get("verbosity")

        aliases = set(options["aliases"])

        if not aliases:
            aliases = settings.CACHES

        for alias in aliases:
            try:
                cache = caches[alias]
            except InvalidCacheBackendError:
                raise CommandError("Cache '{}' does not exist".format(alias))

            if not isinstance(cache, MySQLCache):  # pragma: no cover
                continue

            if verbosity >= 1:
                self.stdout.write(
                    "Deleting from cache '{}'... ".format(alias), ending=""
                )
            num_deleted = cache.cull()
            if verbosity >= 1:
                self.stdout.write("{} entries deleted.".format(num_deleted)) 
開發者ID:adamchainz,項目名稱:django-mysql,代碼行數:26,代碼來源:cull_mysql_caches.py

示例9: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def handle(self, *args, **options):
        aliases = set(options["aliases"])

        if not aliases:
            aliases = settings.CACHES

        tables = set()
        for alias in aliases:
            try:
                cache = caches[alias]
            except InvalidCacheBackendError:
                raise CommandError("Cache '{}' does not exist".format(alias))

            if not isinstance(cache, MySQLCache):  # pragma: no cover
                continue

            tables.add(cache._table)

        if not tables:
            self.stderr.write("No MySQLCache instances in CACHES")
            return

        migration = self.render_migration(tables)
        self.stdout.write(migration) 
開發者ID:adamchainz,項目名稱:django-mysql,代碼行數:26,代碼來源:mysql_cache_migration.py

示例10: cache_qr_code

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def cache_qr_code():
    """
    Decorator that caches the requested page if a settings named 'QR_CODE_CACHE_ALIAS' exists and is not empty or None.
    """
    def decorator(view_func):
        @functools.wraps(view_func)
        def _wrapped_view(request, *view_args, **view_kwargs):
            cache_enabled = request.GET.get('cache_enabled', True)
            if cache_enabled and hasattr(settings, 'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS:
                # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the
                # page.
                timeout = settings.CACHES[settings.QR_CODE_CACHE_ALIAS]['TIMEOUT']
                key_prefix = 'token=%s.user_pk=%s' % (request.GET.get('url_signature_enabled') or constants.DEFAULT_URL_SIGNATURE_ENABLED, request.user.pk)
                response = cache_page(timeout, cache=settings.QR_CODE_CACHE_ALIAS, key_prefix=key_prefix)(view_func)(request, *view_args, **view_kwargs)
            else:
                # No cache alias for storing the generated qr code, call the view as is.
                response = (view_func)(request, *view_args, **view_kwargs)
            return response
        return _wrapped_view
    return decorator 
開發者ID:dprog-philippe-docourt,項目名稱:django-qr-code,代碼行數:22,代碼來源:views.py

示例11: add_arguments

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def add_arguments(self, parser):
        parser.add_argument('args', metavar='table_name', nargs='*',
            help='Optional table names. Otherwise, settings.CACHES is used to '
            'find cache tables.')
        parser.add_argument('--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS,
            help='Nominates a database onto which the cache tables will be '
            'installed. Defaults to the "default" database.') 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:10,代碼來源:createcachetable.py

示例12: handle

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:14,代碼來源:createcachetable.py

示例13: _cache_db_tables_iterator

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def _cache_db_tables_iterator(tables, cache_alias, db_alias):
    no_tables = not tables
    cache_aliases = settings.CACHES if cache_alias is None else (cache_alias,)
    db_aliases = settings.DATABASES if db_alias is None else (db_alias,)
    for db_alias in db_aliases:
        if no_tables:
            tables = connections[db_alias].introspection.table_names()
        if tables:
            for cache_alias in cache_aliases:
                yield cache_alias, db_alias, tables 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:12,代碼來源:api.py

示例14: get_last_invalidation

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def get_last_invalidation(*tables_or_models, **kwargs):
    """
    Returns the timestamp of the most recent invalidation of the given
    ``tables_or_models``.  If ``tables_or_models`` is not specified,
    all tables found in the database (including those outside Django) are used.

    If ``cache_alias`` is specified, it only fetches invalidations
    in this cache, otherwise invalidations in all caches are fetched.

    If ``db_alias`` is specified, it only fetches invalidations
    for this database, otherwise invalidations for all databases are fetched.

    :arg tables_or_models: SQL tables names, models or models lookups
                           (or a combination)
    :type tables_or_models: tuple of strings or models
    :arg cache_alias: Alias from the Django ``CACHES`` setting
    :type cache_alias: string or NoneType
    :arg db_alias: Alias from the Django ``DATABASES`` setting
    :type db_alias: string or NoneType
    :returns: The timestamp of the most recent invalidation
    :rtype: float
    """
    # TODO: Replace with positional arguments when we drop Python 2 support.
    cache_alias = kwargs.pop('cache_alias', None)
    db_alias = kwargs.pop('db_alias', None)
    for k in kwargs:
        raise TypeError("get_last_invalidation() got an unexpected "
                        "keyword argument '%s'" % k)

    last_invalidation = 0.0
    for cache_alias, db_alias, tables in _cache_db_tables_iterator(
            list(_get_tables(tables_or_models)), cache_alias, db_alias):
        get_table_cache_key = cachalot_settings.CACHALOT_TABLE_KEYGEN
        table_cache_keys = [get_table_cache_key(db_alias, t) for t in tables]
        invalidations = cachalot_caches.get_cache(
            cache_alias, db_alias).get_many(table_cache_keys).values()
        if invalidations:
            current_last_invalidation = max(invalidations)
            if current_last_invalidation > last_invalidation:
                last_invalidation = current_last_invalidation
    return last_invalidation 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:43,代碼來源:api.py

示例15: check_cache_compatibility

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import CACHES [as 別名]
def check_cache_compatibility(app_configs, **kwargs):
    cache = settings.CACHES[cachalot_settings.CACHALOT_CACHE]
    cache_backend = cache['BACKEND']
    if cache_backend not in SUPPORTED_CACHE_BACKENDS:
        return [Warning(
            'Cache backend %r is not supported by django-cachalot.'
            % cache_backend,
            hint='Switch to a supported cache backend '
                 'like Redis or Memcached.',
            id='cachalot.W001')]
    return [] 
開發者ID:noripyt,項目名稱:django-cachalot,代碼行數:13,代碼來源:apps.py


注:本文中的django.conf.settings.CACHES屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。