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
 1import click
 2
 3from .models import CachedItem
 4
 5
 6@click.group()
 7def cli():
 8    pass
 9
10
11@cli.command()
12def clear_expired():
13    click.echo("Clearing expired cache items...")
14    result = CachedItem.objects.expired().delete()
15    click.echo(f"Deleted {result[0]} expired cache items.")
16
17
18@cli.command()
19@click.option("--force", is_flag=True)
20def clear_all(force):
21    if not force and not click.confirm(
22        "Are you sure you want to delete all cache items?"
23    ):
24        return
25    click.echo("Clearing all cache items...")
26    result = CachedItem.objects.all().delete()
27    click.echo(f"Deleted {result[0]} cache items.")
28
29
30@cli.command()
31def stats():
32    total = CachedItem.objects.count()
33    expired = CachedItem.objects.expired().count()
34    unexpired = CachedItem.objects.unexpired().count()
35    forever = CachedItem.objects.forever().count()
36
37    click.echo(f"Total: {click.style(total, bold=True)}")
38    click.echo(f"Expired: {click.style(expired, bold=True)}")
39    click.echo(f"Unexpired: {click.style(unexpired, bold=True)}")
40    click.echo(f"Forever: {click.style(forever, bold=True)}")