Cache

cache

缓存的backend可以是django内置的,也可以是第三方的。

  • 缓存整个站点

    MIDDLEWARE = [ ‘django.middleware.cache.UpdateCacheMiddleware’, ‘django.middleware.common.CommonMiddleware’, ‘django.middleware.cache.FetchFromCacheMiddleware’, ]

  • 视图缓存

    from django.views.decorators.cache import cache_page

    @cache_page(60 * 2) def my_view(request): …

    或者在URLconf中指定 urlpatterns = [ path(‘foo/int:code/’, cache_page(60 * 2)(my_view)), ]

  • 模板片段缓存

    {% load cache %} {% cache … %} … {% endcache %}


redis

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get("REDIS_URL", ''),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
        "TIMEOUT": 60,
    }
}

memcached

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

database

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}
Designed by Canux