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 import models
 2from plain.utils import timezone
 3
 4
 5class CachedItemQuerySet(models.QuerySet):
 6    def expired(self):
 7        return self.filter(expires_at__lt=timezone.now())
 8
 9    def unexpired(self):
10        return self.filter(expires_at__gte=timezone.now())
11
12    def forever(self):
13        return self.filter(expires_at=None)
14
15
16class CachedItem(models.Model):
17    key = models.CharField(max_length=255, unique=True)
18    value = models.JSONField(blank=True, null=True)
19    expires_at = models.DateTimeField(blank=True, null=True, db_index=True)
20    created_at = models.DateTimeField(auto_now_add=True)
21    updated_at = models.DateTimeField(auto_now=True)
22
23    objects = CachedItemQuerySet.as_manager()
24
25    def __str__(self) -> str:
26        return self.key