FastAPI simple cache

Overview

FastAPI Cache

Codacy Badge License PyPi Version Downloads Build Status

Implements simple lightweight cache system as dependencies in FastAPI.

Installation

pip install fastapi-cache

Usage example

from fastapi import Depends, FastAPI

from fastapi_cache import caches, close_caches
from fastapi_cache.backends.redis import CACHE_KEY, RedisCacheBackend

app = FastAPI()


def redis_cache():
    return caches.get(CACHE_KEY)


@app.get('/')
async def hello(
    cache: RedisCacheBackend = Depends(redis_cache)
):
    in_cache = await cache.get('some_cached_key')
    if not in_cache:
        await cache.set('some_cached_key', 'new_value', 5)

    return {'response': in_cache or 'default'}


@app.on_event('startup')
async def on_startup() -> None:
    rc = RedisCacheBackend('redis://redis')
    caches.set(CACHE_KEY, rc)


@app.on_event('shutdown')
async def on_shutdown() -> None:
    await close_caches()

TODO

  • Add tests
  • Add registry decorator
  • Add dependency for requests caching

Acknowledgments

  • Balburdia
  • xobtoor

Changelog

  • 0.0.6 Added typings for backends. Specific arguments now need to be passed through **kwargs. Set default encoding to utf-8 for redis backend, removed default TTL for redis keys.
Comments
  • Add support for caching generic types

    Add support for caching generic types

    Reference Issues/PRs

    None

    What does this implement/fix?

    The current version of the package fails to retrieve objects in Redis that cannot be decoded by the default encoding='utf-8' option defined on get. In order to enable a more generic approach this PR refactor the Cache classes changing the value typing (both when setting and when retrieving) to Any, minimizing IDE's warnings, and adds a new optional parameter encoding to RedisCacheBackend.get method, keeping utf-8 as the default value to enable backwards compatibility. A new simple test for the option encoding=None was added.

    opened by Balburdia 3
  • Add support for Redis backend requiring TLS

    Add support for Redis backend requiring TLS

    It looks like the RedisCacheBackend doesn't support specifying the ssl passthrough option to aioredis.create_redis_pool() in order to be able to connect to a Redis endpoint that requires TLS, e.g. ElastiCache in AWS.

    opened by erhhung 1
  • Create expire function

    Create expire function

    This PR will include the aioredis function for expire(key, timeout) in order to automatically invalidate an entry after some time. This is useful when using redis for caching API responses.

    enhancement 
    opened by jersobh 0
  • Add redis function to check if key exists or not

    Add redis function to check if key exists or not

    in our current implementation of redis we use exists a lot to check if a key is already set or not and then decide what to do.

    exists can check multiple keys at once and returns an integer with the number of existing keys.

    https://redis.io/commands/exists

    enhancement 
    opened by stndrf 0
  • How to pass a KEYS pattern when get cache [Redis Backend]?

    How to pass a KEYS pattern when get cache [Redis Backend]?

    Hi guys, I couldn't find anywhere how I can get values from a given key with a pattern. Eg.: project_* where * can be any char.

    I tried something like await cache.get("project_*") but no success.

    Reference: https://redis.io/commands/KEYS

    opened by mauricioribeiro 0
  • Upgrade aioredis to 2.x

    Upgrade aioredis to 2.x

    aioredis 2.x introduces breaking changes in API

    • poo_min_size is dropped, the connection pool is now lazy filled, not pre-filled
    • whether decode or not is decided globally, could not be changed on each top level api (like Redis.get())
    opened by laggardkernel 0
  • ImportError: cannot import name 'FastAPICache' from 'fastapi_cache'

    ImportError: cannot import name 'FastAPICache' from 'fastapi_cache'

    I have the following issue when try running the API from my docker image. Running it locally, has no issue.

    This is my requirements.txt:

    fastapi==0.63.0
    fastapi-cache==0.1.0
    

    Full error message:

    from api.routers import sa_ranking, sa_person_ranking
      File "./api/routers/sa_ranking.py", line 9, in <module>
        from fastapi_cache import FastAPICache
    ImportError: cannot import name 'FastAPICache' from 'fastapi_cache' (/usr/local/lib/python3.8/site-packages/fastapi_cache/__init__.py)
    

    Please help! Urgent need

    opened by chenuratikah 1
  • Can we remove print statement in InMemoryCache?

    Can we remove print statement in InMemoryCache?

    Would it possible to remove below print statements https://github.com/comeuplater/fastapi_cache/blob/2723817a5d6f7d34c736acd09b155c05cd1221d3/fastapi_cache/backends/utils/ttldict.py#L14

    https://github.com/comeuplater/fastapi_cache/blob/2723817a5d6f7d34c736acd09b155c05cd1221d3/fastapi_cache/backends/utils/ttldict.py#L28

    bug 
    opened by herbherbherb 0
Releases(0.0.1)
Owner
Ivan Sushkov
Ivan Sushkov
This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

This is an API developed in python with the FastApi framework and putting into practice the recommendations of the book Clean Architecture in Python by Leonardo Giordani,

0 Sep 24, 2022
Asynchronous event dispatching/handling library for FastAPI and Starlette

fastapi-events An event dispatching/handling library for FastAPI, and Starlette. Features: straightforward API to emit events anywhere in your code ev

Melvin 238 Jan 07, 2023
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 49 Dec 03, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 562 Jan 01, 2023
Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as a REST API Endpoint.

Jupter Notebook REST API Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as

Invictify 54 Nov 04, 2022
FastAPI client generator

FastAPI-based API Client Generator Generate a mypy- and IDE-friendly API client from an OpenAPI spec. Sync and async interfaces are both available Com

David Montague 283 Jan 04, 2023
Fast, simple API for Apple firmwares.

Loyal Fast, Simple API for fetching Apple Firmwares. The API server is closed due to some reasons. Wait for v2 releases. Features Fetching Signed IPSW

11 Oct 28, 2022
FastAPI interesting concepts.

fastapi_related_stuffs FastAPI interesting concepts. FastAPI version :- 0.70 Python3 version :- 3.9.x Steps Test Django Like settings export FASTAPI_S

Mohd Mujtaba 3 Feb 06, 2022
A kedro-plugin to serve Kedro Pipelines as API

General informations Software repository Latest release Total downloads Pypi Code health Branch Tests Coverage Links Documentation Deployment Activity

Yolan Honoré-Rougé 12 Jul 15, 2022
Flood Detection with Google Earth Engine

ee-fastapi: Flood Detection System A ee-fastapi is a simple FastAPI web application for performing flood detection using Google Earth Engine in the ba

Cesar Aybar 69 Jan 06, 2023
Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

José Antonio Perdiguero 229 Dec 21, 2022
REST API with FastAPI and JSON file.

FastAPI RESTAPI with a JSON py 3.10 First, to install all dependencies, in ./src/: python -m pip install -r requirements.txt Second, into the ./src/

Luis Quiñones Requelme 1 Dec 15, 2021
Drop-in MessagePack support for ASGI applications and frameworks

msgpack-asgi msgpack-asgi allows you to add automatic MessagePack content negotiation to ASGI applications (Starlette, FastAPI, Quart, etc.), with a s

Florimond Manca 128 Jan 02, 2023
User authentication fastapi with python

user-authentication-fastapi Authentication API Development Setup environment You should create a virtual environment and activate it: virtualenv venv

Sabir Hussain 3 Mar 03, 2022
The template for building scalable web APIs based on FastAPI, Tortoise ORM and other.

FastAPI and Tortoise ORM. Powerful but simple template for web APIs w/ FastAPI (as web framework) and Tortoise-ORM (for working via database without h

prostomarkeloff 95 Jan 08, 2023
API written using Fast API to manage events and implement a leaderboard / badge system.

Open Food Facts Events API written using Fast API to manage events and implement a leaderboard / badge system. Installation To run the API locally, ru

Open Food Facts 5 Jan 07, 2023
FastAPI native extension, easy and simple JWT auth

fastapi-jwt FastAPI native extension, easy and simple JWT auth

Konstantin Chernyshev 19 Dec 12, 2022
FastAPI CRUD template using Deta Base

Deta Base FastAPI CRUD FastAPI CRUD template using Deta Base Setup Install the requirements for the CRUD: pip3 install -r requirements.txt Add your D

Sebastian Ponce 2 Dec 15, 2021
FastAPI simple cache

FastAPI Cache Implements simple lightweight cache system as dependencies in FastAPI. Installation pip install fastapi-cache Usage example from fastapi

Ivan Sushkov 188 Dec 29, 2022
Sample project showing reliable data ingestion application using FastAPI and dramatiq

Create and deploy a reliable data ingestion service with FastAPI, SQLModel and Dramatiq This is the source code for the data ingestion service explain

François Voron 31 Nov 30, 2022