Asynchronous cache manager designed for horizontally scaled web servers.

Related tags

Caching atomcache
Overview

Introduction

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

Requirements

Python 3.7+

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:
Callable: async def stop_app() -> None: await Cache.backend.close() return stop_app ">
from typing import Optional, Callable

import aioredis
from fastapi import FastAPI, Depends
from atomcache import Cache


def create_start_app_handler(app: FastAPI) -> Callable:
    async def start_app() -> None:
        redis: aioredis.Redis = await aioredis.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:

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 [] ">
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 []
You might also like...
YOLOv4 / Scaled-YOLOv4 / YOLO - Neural Networks for Object Detection (Windows and Linux version of Darknet )
YOLOv4 / Scaled-YOLOv4 / YOLO - Neural Networks for Object Detection (Windows and Linux version of Darknet )

Yolo v4, v3 and v2 for Windows and Linux (neural networks for object detection) Paper YOLO v4: https://arxiv.org/abs/2004.10934 Paper Scaled YOLO v4:

SE-MSCNN: A Lightweight Multi-scaled Fusion Network for Sleep Apnea Detection Using Single-Lead ECG Signals
SE-MSCNN: A Lightweight Multi-scaled Fusion Network for Sleep Apnea Detection Using Single-Lead ECG Signals

SE-MSCNN: A Lightweight Multi-scaled Fusion Network for Sleep Apnea Detection Using Single-Lead ECG Signals Abstract Sleep apnea (SA) is a common slee

A Python dictionary implementation designed to act as an in-memory cache for FaaS environments

faas-cache-dict A Python dictionary implementation designed to act as an in-memory cache for FaaS environments. Formally you would describe this a mem

Migration Manager (MM) is a very small utility that can list source servers in a target account and apply mass launch template modifications.

Migration Manager Migration Manager (MM) is a very small utility that can list source servers in a target account and apply mass launch template modif

Robot Servers and Server Manager software for robo-gym

robo-gym-server-modules Robot Servers and Server Manager software for robo-gym. For info on how to use this package please visit the robo-gym website

📦 Powerful Package manager which updates plugins & server software for minecraft servers
📦 Powerful Package manager which updates plugins & server software for minecraft servers

pluGET A powerful package manager which updates Plugins and Server Software for minecraft servers. Screenshots check all to check installed plugins fo

Game code for Evennia servers designed for use with ALPACASclient.
Game code for Evennia servers designed for use with ALPACASclient.

ALPACASgame Game code for Evennia servers designed for use with ALPACASclient. This code is meant to be a type of "compatability layer" between the AL

Installer, package manager, build wrapper and version manager for Piccolo

Piccl Installer, package manager, build wrapper and version manager for Piccolo

A simple and easy to use Python's PIP configuration manager, similar to the Arch Linux's Java manager.
A simple and easy to use Python's PIP configuration manager, similar to the Arch Linux's Java manager.

PIPCONF - The PIP configuration manager If you need to manage multiple configurations containing indexes and trusted hosts for PIP, this project was m

File-manager - A basic file manager, written in Python

File Manager A basic file manager, written in Python. Installation Install Pytho

Expense-manager - Expense manager with python

Expense_manager TO-DO Source extractor: Credit Card, Wallet Destination extracto

Designed and coded a password manager in Python with Arduino integration

Designed and coded a password manager in Python with Arduino integration. The Program uses a master user to login, and stores account data such as usernames and passwords to the master user. While logging into the program with the master user the Arduino was used as a two-factor authentication key. The program detects a connection to the Arduino and checks if certain parameters are met before completing the login procedure.

Pacman-AI - AI project designed by UC Berkeley. Designed reflex and minimax agents for the game Pacman.
Pacman-AI - AI project designed by UC Berkeley. Designed reflex and minimax agents for the game Pacman.

Pacman AI Jussi Doherty CAP 4601 - Introduction to Artificial Intelligence - Fall 2020 Python version 3.0+ Source of this project This repo contains a

A training task for web scraping using python multithreading and a real-time-updated list of available proxy servers.

Parallel web scraping The project is a training task for web scraping using python multithreading and a real-time-updated list of available proxy serv

Fast, asynchronous and elegant Python web framework.
Fast, asynchronous and elegant Python web framework.

Warning: This project is being completely re-written. If you're curious about the progress, reach me on Slack. Vibora is a fast, asynchronous and eleg

cirrina is an opinionated asynchronous web framework based on aiohttp
cirrina is an opinionated asynchronous web framework based on aiohttp

cirrina cirrina is an opinionated asynchronous web framework based on aiohttp. Features: HTTP Server Websocket Server JSON RPC Server Shared sessions

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Tornado Web Server Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. By using non-blocking ne

Meinheld is a high performance asynchronous WSGI Web Server (based on picoev)

What's this This is a high performance python wsgi web server. And Meinheld is a WSGI compliant web server. (PEP333 and PEP3333 supported) You can als

Comments
  • Bump fastapi from 0.61.2 to 0.65.2

    Bump fastapi from 0.61.2 to 0.65.2

    Bumps fastapi from 0.61.2 to 0.65.2.

    Release notes

    Sourced from fastapi's releases.

    0.65.2

    Security fixes

    This change fixes a CSRF security vulnerability when using cookies for authentication in path operations with JSON payloads sent by browsers.

    In versions lower than 0.65.2, FastAPI would try to read the request payload as JSON even if the content-type header sent was not set to application/json or a compatible JSON media type (e.g. application/geo+json).

    So, a request with a content type of text/plain containing JSON data would be accepted and the JSON data would be extracted.

    But requests with content type text/plain are exempt from CORS preflights, for being considered Simple requests. So, the browser would execute them right away including cookies, and the text content could be a JSON string that would be parsed and accepted by the FastAPI application.

    See CVE-2021-32677 for more details.

    Thanks to Dima Boger for the security report! 🙇🔒

    Internal

    0.65.1

    Security fixes

    0.65.0

    Breaking Changes - Upgrade

    • ⬆️ Upgrade Starlette to 0.14.2, including internal UJSONResponse migrated from Starlette. This includes several bug fixes and features from Starlette. PR #2335 by @​hanneskuettner.

    Translations

    Internal

    0.64.0

    Features

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 2
Owner
Serghei
Serghei
Python disk-backed cache (Django-compatible). Faster than Redis and Memcached. Pure-Python.

DiskCache is an Apache2 licensed disk and file backed cache library, written in pure-Python, and compatible with Django.

Grant Jenks 1.7k Jan 5, 2023
An ORM cache for Django.

Django ORMCache A cache manager mixin that provides some caching of objects for the ORM. Installation / Setup / Usage TODO Testing Run the tests with:

Educreations, Inc 15 Nov 27, 2022
A Redis cache backend for django

Redis Django Cache Backend A Redis cache backend for Django Docs can be found at http://django-redis-cache.readthedocs.org/en/latest/. Changelog 3.0.0

Sean Bleier 1k Dec 15, 2022
johnny cache django caching framework

Johnny Cache is a caching framework for django applications. It works with the django caching abstraction, but was developed specifically with the use

Jason Moiron 304 Nov 7, 2022
RecRoom Library Cache Tool

RecRoom Library Cache Tool A handy tool to deal with the Library cache file. Features Parse Library cache Remove Library cache Parsing The script pars

Jesse 5 Jul 9, 2022
Peerix is a peer-to-peer binary cache for nix derivations

Peerix Peerix is a peer-to-peer binary cache for nix derivations. Every participating node can pull derivations from each other instances' respective

null 92 Dec 13, 2022
Robust, highly tunable and easy-to-integrate in-memory cache solution written in pure Python, with no dependencies.

Omoide Cache Caching doesn't need to be hard anymore. With just a few lines of code Omoide Cache will instantly bring your Python services to the next

Leo Ertuna 2 Aug 14, 2022
Django package to log request values such as device, IP address, user CPU time, system CPU time, No of queries, SQL time, no of cache calls, missing, setting data cache calls for a particular URL with a basic UI.

django-web-profiler's documentation: Introduction: django-web-profiler is a django profiling tool which logs, stores debug toolbar statistics and also

MicroPyramid 77 Oct 29, 2022
Jira-cache - Jira cache with python

Direct queries to Jira have two issues: they are sloooooow many queries are impo

John Scott 6 Oct 8, 2022
Implementation of "Scaled-YOLOv4: Scaling Cross Stage Partial Network" using PyTorch framwork.

YOLOv4-large This is the implementation of "Scaled-YOLOv4: Scaling Cross Stage Partial Network" using PyTorch framwork. YOLOv4-CSP YOLOv4-tiny YOLOv4-

Kin-Yiu, Wong 2k Jan 2, 2023