Plain is headed towards 1.0! Subscribe for development updates →

Cache

A simple cache using the database.

The Plain Cache stores JSON-serializable values in a CachedItem model. Cached data can be set to expire after a certain amount of time.

Access to the cache is provided through the Cached class.

from plain.cache import Cached


cached = Cached("my-cache-key")

if cached.exists():
    print("Cache hit and not expired!")
    print(cached.value)
else:
    print("Cache miss!")
    cached.set("a JSON-serializable value", expiration=60)

# Delete the item if you need to
cached.delete()

Expired cache items can be cleared with plain cache clear-expired. You can run this on a schedule through various cron-like tools or plain-worker.

Installation

Add plain.cache to your INSTALLED_PACKAGES:

# app/settings.py
INSTALLED_PACKAGES = [
    # ...
    "plain.cache",
]

CLI

  • plain cache clear-expired - Clear all expired cache items
  • plain cache clear-all - Clear all cache items
  • plain cache stats - Show cache statistics
 1from plain.cache.models import CachedItem
 2from plain.staff.views import (
 3    StaffModelDetailView,
 4    StaffModelListView,
 5    StaffModelViewset,
 6    register_viewset,
 7)
 8
 9
10@register_viewset
11class CachedItemViewset(StaffModelViewset):
12    class ListView(StaffModelListView):
13        nav_section = "Cache"
14        model = CachedItem
15        title = "Cached items"
16        fields = [
17            "key",
18            "created_at",
19            "expires_at",
20            "updated_at",
21        ]
22        queryset_order = ["-pk"]
23        allow_global_search = False
24
25        def get_list_queryset(self):
26            return CachedItem.objects.all().only(
27                "key", "created_at", "expires_at", "updated_at"
28            )
29
30    class DetailView(StaffModelDetailView):
31        model = CachedItem
32        title = "Cached item"