ring.django — Django support

ring.django.cache(backend=<django.utils.connection.ConnectionProxy object>, key_prefix=None, expire=None, coder=None, user_interface=<class 'ring.func.sync.CacheUserInterface'>, storage_class=<class 'ring.django.LowLevelCacheStorage'>)

A typical ring-style cache based on Django’s low-level cache API.

Parameters:backend (Union[str,object]) – Django’s cache config key for django.core.cache.caches or Django cache object.
See:Django’s cache framework: Setting up the cache to configure django cache.
See:Django’s cache framework: The low-level cache API for the backend.
ring.django.cache_page(timeout, cache=None, key_prefix=None, user_interface=<class 'ring.django.CachePageUserInterface'>, storage_class=<class 'ring.func.base.BaseStorage'>)

The drop-in-replacement of Django’s per-view cache.

Use this decorator instead of django.views.decorators.cache.cache_page(). The decorated view function itself is compatible. Ring decorated function additionally have ring-styled sub-functions. In the common cases, delete and update are helpful.

  • timeout (float) – Same as timeout of Django’s cache_page.
  • cache (Optional[str]) – Same as cache of Django’s cache_page.
  • key_prefix (str) – Same as key_prefix of Django’s cache_page.

Here is an example of delete sub-function.

def article_list(request):
    articles = ...
    return HttpResponse(
        template.render({'articles': articles}, request))

def article_post(request):
    article = ...  # create a new article
    article_list.delete((request, 'article_list'))  # DELETE!
    return ...

Compare to how Django originally invalidate it.

def article_post_django(request):
    articles = ...

    from django.core.cache import cache
    from django.utils.cache import get_cache_key
    fake_request = HttpRequest()  # a fake request
    fake_request.__dict__.update(request.__dict__)  # not mandatory by env
    fake_request.method = 'GET'
    fake_request.path = reverse('article_list')
    key = get_cache_key(request)

    return ...

Note that the first parameter of every sub-function originally is a django.request.HttpRequest object but a tuple here. The second item of the tuple provides a hint for the request path of article_list. Because Django expects the cache key varies by request path, it is required to find the corresponding cache key.

See:Django’s cache framework: The per-view cache
class ring.django.LowLevelCacheStorage(ring, backend)

Storage implementation for django.core.cache.caches.

class ring.django.CachePageUserInterface(ring)

Django per-view cache interface.

Note:This interface doesn’t require any storage backend.

The interface imitates the behavior of django.views.decorators.cache.cache_page(). The code is mostly parts of fragmented django.utils.decorators.make_middleware_decorator() except for key, delete and has.