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
An extension library for FastAPI framework

FastLab An extension library for FastAPI framework Features Logging Models Utils Routers Installation use pip to install the package: pip install fast

Tezign Lab 10 Jul 11, 2022
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Rene Dohmen 63 Dec 30, 2022
Fastapi-ml-template - Fastapi ml template with python

FastAPI ML Template Run Web API Local $ sh run.sh # poetry run uvicorn app.mai

Yuki Okuda 29 Nov 20, 2022
A simple Blogging Backend app created with Fast API

This is a simple blogging app backend built with FastAPI. This project is created to simulate a real CRUD blogging system. It is built to be used by s

Owusu Kelvin Clark 13 Mar 24, 2022
An alternative implement of Imjad API | Imjad API 的开源替代

HibiAPI An alternative implement of Imjad API. Imjad API 的开源替代. 前言 由于Imjad API这是什么?使用人数过多, 致使调用超出限制, 所以本人希望提供一个开源替代来供社区进行自由的部署和使用, 从而减轻一部分该API的使用压力 优势

Mix Technology 450 Dec 29, 2022
Lazy package to start your project using FastAPI✨

Fastapi-lazy 🦥 Utilities that you use in various projects made in FastAPI. Source Code: https://github.com/yezz123/fastapi-lazy Install the project:

Yasser Tahiri 95 Dec 29, 2022
A comprehensive CRUD API generator for SQLALchemy.

FastAPI Quick CRUD Introduction Advantage Constraint Getting started Installation Usage Design Path Parameter Query Parameter Request Body Upsert Intr

192 Jan 06, 2023
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 273 Dec 01, 2022
A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits

A FastAPI Framework for things like Database, Redis, Logging, JWT Authentication and Rate Limits Install You can install this Library with: pip instal

Tert0 33 Nov 28, 2022
Simple example of FastAPI + Celery + Triton for benchmarking

You can see the previous work from: https://github.com/Curt-Park/producer-consumer-fastapi-celery https://github.com/Curt-Park/triton-inference-server

Jinwoo Park (Curt) 37 Dec 29, 2022
Twitter API monitor with fastAPI + MongoDB

Twitter API monitor with fastAPI + MongoDB You need to have a file .env with the following variables: DB_URL="mongodb+srv://mongodb_path" DB_URL2=

Leonardo Ferreira 3 Apr 08, 2022
A FastAPI Middleware of joerick/pyinstrument to check your service performance.

fastapi_profiler A FastAPI Middleware of joerick/pyinstrument to check your service performance. 📣 Info A FastAPI Middleware of pyinstrument to check

LeoSun 107 Jan 05, 2023
FastAPI pagination

FastAPI Pagination Installation # Basic version pip install fastapi-pagination # All available integrations pip install fastapi-pagination[all] Avail

Yurii Karabas 561 Jan 07, 2023
Town / City geolocations with FastAPI & Mongo

geolocations-api United Kingdom Town / City geolocations with FastAPI & Mongo Build container To build a custom image or extend the api run the follow

Joe Gasewicz 3 Jan 26, 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
A simple Redis Streams backed Chat app using Websockets, Asyncio and FastAPI/Starlette.

redis-streams-fastapi-chat A simple demo of Redis Streams backed Chat app using Websockets, Python Asyncio and FastAPI/Starlette. Requires Python vers

ludwig404 135 Dec 19, 2022
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
Keycloak integration for Python FastAPI

FastAPI Keycloak Integration Documentation Introduction Welcome to fastapi-keycloak. This projects goal is to ease the integration of Keycloak (OpenID

Code Specialist 113 Dec 31, 2022
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

FastAPI Ariadne Example Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI - GitHub ###Запуск на локальном окру

ZeBrains Team 9 Nov 10, 2022
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