Skip to main content

Package version Supported Python versions

Introduction

Asynchronous cache manager designed for horizontally scaled web applications. NOTE: Currently has implementation only for FastAPI using Redis.

Requirements

Python 3.7+

  • redis for cache implementation.
  • FastAPI for the web parts.

Installation

$ pip install atomcache

---> 100%

Explanation schema

Class Diagram

As UML
@startuml
    !theme materia
    participant Redis
    participant Instance_A as A
    participant Instance_B as B
    participant Instance_N as C


    B <-> Redis: GET: Cache=null & GET: Lock=null

    B <-> Redis: SET: Lock = true

    activate B #Red
    A <--> Redis: GET: Cache=null & GET: Lock=true
    activate A #Transparent
    C <--> Redis: GET: Cache=null & GET: Lock=true
    activate C #Transparent
    B <--> B: Do the computation
    B -> Redis: SET: Cache={...}
    deactivate B

    group Notify Cache SET
        Redis -> C
        Redis -> A
    end
    group GET Cache
        Redis <-> C
    deactivate C
        Redis <-> A
    deactivate A
    end
@enduml

Examples:

Usage as FastAPI Dependency

  • Create a file events.py with:
from typing import Optional, Callable

from redis.asyncio import Redis
from fastapi import FastAPI, Depends
from atomcache import Cache


def create_start_app_handler(app: FastAPI) -> Callable:
    async def start_app() -> None:
        redis: Redis = await Redis.from_url(url="redis://localhost", encoding="utf-8")
        await Cache.init(app, redis)

    return start_app


def create_stop_app_handler(app: FastAPI) -> Callable:
    async def stop_app() -> None:
        await Cache.backend.close()

    return stop_app
  • Create a file main.py with:
from typing import Optional

from fastapi import FastAPI, Depends
from atomcache import Cache

from .events import create_start_app_handler, create_stop_app_handler

app = FastAPI()

app.add_event_handler("startup", create_start_app_handler(app))
app.add_event_handler("shutdown", create_stop_app_handler(app))


@router.get("/resources", response_model=List[TheResponseModel], name="main:test-example")
async def resources(offset: int = 0, items: int = 10, cache: Cache = Depends(Cache(exp=600)):
    cache_id = f"{offset}-{items}"  # Build cache identifier
    await cache.raise_try(cache_id)  # Try to respond from cache
    response = await db.find(TheResponseModel, skip=offset, limit=items)
    await asyncio.sleep(10)  # Do some heavy work for 10 sec, see `lock_timeout`
    return cache.set(response, cache_id=cache_id)

Direct cache usage for avoiding repetitive calling on external resources:

from aiohttp import ClientSession
from atomcache import Cache

cache = Cache(exp=1200, namespace="my-namespace:")


async def requesting_helper(ref: str) -> List[dict]:
    cached_value = await cache.get(cache_id=ref)
    if cached_value is not None:
        return cached_value

    async with ClientSession() as session:
        async with session.get(f"https://external-api.io/{ref}") as response:
            if response.ok:
                cached_value = response.json()
                return cache.set(cached_value, cache_id=ref)
    return []

Metadata

Release files for atomcache 0.7.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for atomcache 0.7.6
File Size Uploaded
atomcache-0.7.6.tar.gz 9.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for atomcache 0.7.6
File Interpreter ABI Platform
atomcache-0.7.6-py3-none-any.whl Python 3 none any Details

Total release size: 18.3 kB

Release files / atomcache-0.7.6.tar.gz

Download URL atomcache-0.7.6.tar.gz
Size 9.1 kB
Tags Source
SHA-256 checksum
How to use checksums
b58eb29626644a51c227990e62df33633a8b9049e5a5efd4c75c6c6c79be0c05
BLAKE2b-256 checksum
How to use checksums
7aa55703c4ed070a79bb600f90c9fba5ebdae76c5988ec6053b9f950a8c99f59
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.0 CPython/3.11.6 Linux/6.5.0-26-generic

Release files / atomcache-0.7.6-py3-none-any.whl

Download URL atomcache-0.7.6-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
05afefd68b2e69590fbb59f236153c1ba8d6c32e87f657f1bb62cc6352ecb4b8
BLAKE2b-256 checksum
How to use checksums
8d4d5d8e1f66697cefc2a6c89c88ac12b63b8b1b714c230bdbb3ec58a6b6af90
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.0 CPython/3.11.6 Linux/6.5.0-26-generic

Release history Release notifications | RSS feed

This release

0.7.6 This release

2 release files

0.7.5

2 release files

0.7.4

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.11

2 release files

0.5.10

2 release files

0.5.9

2 release files

0.5.8

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page