Skip to main content

Simple cache with pydantic.

Project description

cachetic

PyPI version Python Version License

A simple, type-safe caching library supporting Redis and disk storage with automatic Pydantic serialization.

Features

  • Type-safe: Full type checking with generic support
  • Flexible backends: Local disk cache (diskcache) or Redis
  • Pydantic integration: Automatic serialization for any type via TypeAdapter
  • Compression support: Optional zstd/zlib compression with automatic detection
  • Simple API: Just get() and set() with optional TTL

Installation

pip install cachetic

Quick Start

Basic Usage

import pydantic
from cachetic import Cachetic

# Define your model
class Person(pydantic.BaseModel):
    name: str
    age: int

# Create cache instance
cache = Cachetic[Person](
    object_type=pydantic.TypeAdapter(Person),
    cache_url=".cache"  # Local disk cache
)

# Store and retrieve
person = Person(name="Alice", age=30)
cache.set("user:1", person)

result = cache.get("user:1")
print(result.name)  # "Alice"

Redis Backend

cache = Cachetic[Person](
    object_type=pydantic.TypeAdapter(Person),
    cache_url="redis://localhost:6379/0"
)

Primitive Types

# String cache
str_cache = Cachetic[str](
    object_type=pydantic.TypeAdapter(str),
    cache_url=".cache"
)

str_cache.set("greeting", "Hello, World!")
print(str_cache.get("greeting"))  # "Hello, World!"

# List cache
list_cache = Cachetic[list[str]](
    object_type=pydantic.TypeAdapter(list[str]),
    cache_url=".cache"
)

list_cache.set("items", ["apple", "banana", "cherry"])

Complex Types

from typing import Dict, List

# Dictionary cache
data = {"users": [{"id": 1, "name": "Alice"}], "total": 1}
dict_cache = Cachetic[Dict](
    object_type=pydantic.TypeAdapter(Dict),
    cache_url=".cache"
)

dict_cache.set("user_data", data)

# List of models
people_cache = Cachetic[List[Person]](
    object_type=pydantic.TypeAdapter(List[Person]),
    cache_url=".cache"
)

people = [Person(name="Alice", age=30), Person(name="Bob", age=25)]
people_cache.set("team", people)

Compression Support

Enable compression to reduce storage space and bandwidth usage:

# Enable compression (auto-selects best algorithm)
cache = Cachetic[Person](
    object_type=pydantic.TypeAdapter(Person),
    cache_url=".cache",
    compression=True  # New in v0.5.0
)

person = Person(name="Alice", age=30)
cache.set("user:1", person)  # Automatically compressed
result = cache.get("user:1")  # Automatically decompressed

Compression Algorithms:

  • zstd (preferred): Used if zstandard package is installed
  • zlib (fallback): Built-in Python standard library

Automatic Detection:

  • Caches with compression=False can still read compressed data
  • Automatic decompression occurs when compressed data is detected
  • Seamless migration between compressed and uncompressed caches

Installation with zstd support:

pip install cachetic zstandard

Configuration

Constructor Parameters

  • object_type: pydantic.TypeAdapter[T] - Required type adapter for serialization
  • cache_url: Cache backend - file path for disk cache or redis://... for Redis
  • default_ttl: Default expiration in seconds (-1 = no expiration, 0 = disabled)
  • prefix: Key prefix for all cache operations
  • compression: Enable compression for cached values (default: False)

TTL Examples

# No expiration (default)
cache = Cachetic[str](
    object_type=pydantic.TypeAdapter(str),
    default_ttl=-1
)

# 1 hour expiration
cache = Cachetic[str](
    object_type=pydantic.TypeAdapter(str),
    default_ttl=3600
)

# Per-operation TTL
cache.set("key", "value", ex=300)  # 5 minutes

Environment Variables

Use CACHETIC_ prefix:

export CACHETIC_CACHE_URL="redis://localhost:6379/0"
export CACHETIC_DEFAULT_TTL=3600
export CACHETIC_PREFIX="myapp"
export CACHETIC_COMPRESSION=true

Error Handling

from cachetic import CacheNotFoundError

# get() returns None for missing keys
result = cache.get("nonexistent")  # None

# get_or_raise() throws exception
try:
    result = cache.get_or_raise("nonexistent")
except CacheNotFoundError:
    print("Key not found")

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cachetic-0.5.0.tar.gz (9.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cachetic-0.5.0-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

Details for the file cachetic-0.5.0.tar.gz.

File metadata

  • Download URL: cachetic-0.5.0.tar.gz
  • Upload date:
  • Size: 9.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.11.11 Darwin/25.1.0

File hashes

Hashes for cachetic-0.5.0.tar.gz
Algorithm Hash digest
SHA256 cd4e722b3bc9e6d9239c4eb9b83bb79d72e71d4a60ab6c0408fd6dfb6f1a49b7
MD5 5ab2610b7c9bfd97dc3243048f825017
BLAKE2b-256 bda0ee72f91aef86ac07027ad4743c52e85d3a0bd986bcf2e0d82543505c01cb

See more details on using hashes here.

File details

Details for the file cachetic-0.5.0-py3-none-any.whl.

File metadata

  • Download URL: cachetic-0.5.0-py3-none-any.whl
  • Upload date:
  • Size: 11.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.11.11 Darwin/25.1.0

File hashes

Hashes for cachetic-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0310b87942134e12addd7e5804192c083bcf4c4c63bf1ecc588c81855407d5e0
MD5 fad5aa86573f286fda46450d8d62e6e0
BLAKE2b-256 f0d2f3299d8981a986d4718accf0439780c8b81c6cdd8048d0ad774b890994b5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page