Skip to main content

Asynchronous cache manager designed for horizontally scaled web applications.

Project description

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 []

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

atomcache-0.7.3.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

atomcache-0.7.3-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

Details for the file atomcache-0.7.3.tar.gz.

File metadata

  • Download URL: atomcache-0.7.3.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.11.0rc1 Linux/5.16.11-051611-lowlatency

File hashes

Hashes for atomcache-0.7.3.tar.gz
Algorithm Hash digest
SHA256 a2be4d14efdcef199c325ce05c4edbe358cda0e4eb98bcd8aefa5b7b50a420ae
MD5 8ce009174ab2297053a8c0e0d89bc2cf
BLAKE2b-256 5821c50ca7f226b9df085b73b55a7b679df8514077db18fafbf07a046fec955e

See more details on using hashes here.

File details

Details for the file atomcache-0.7.3-py3-none-any.whl.

File metadata

  • Download URL: atomcache-0.7.3-py3-none-any.whl
  • Upload date:
  • Size: 9.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.5.1 CPython/3.11.0rc1 Linux/5.16.11-051611-lowlatency

File hashes

Hashes for atomcache-0.7.3-py3-none-any.whl
Algorithm Hash digest
SHA256 4c3cf0b41f8cac1bcc3dcc41c27435d310c0b620dbbe73238a632ab4ed834e39
MD5 58af34ae2490243a7f1a3cf41c016f65
BLAKE2b-256 8462ff28d7440b92a4ece20fbf2bb78cb9f0ccdd84250a25602ede6f7a0588e0

See more details on using hashes here.

Supported by

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