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 code generator creates FastAPI app from an openapi file.

fastapi-code-generator This code generator creates FastAPI app from an openapi file. This project is an experimental phase. fastapi-code-generator use

Koudai Aono 632 Jan 05, 2023
API using python and Fastapi framework

Welcome 👋 CFCApi is a API DEVELOPMENT PROJECT UNDER CODE FOR COMMUNITY ! Project Walkthrough 🚀 CFCApi run on Python using FASTapi Framework Docs The

Abhishek kushwaha 7 Jan 02, 2023
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Tomasz Wójcik 300 Dec 26, 2022
A Python framework to build Slack apps in a flash with the latest platform features.

Bolt for Python A Python framework to build Slack apps in a flash with the latest platform features. Read the getting started guide and look at our co

SlackAPI 684 Jan 09, 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
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
API for Submarino store

submarino-api API for the submarino e-commerce documentation read the documentation in: https://submarino-api.herokuapp.com/docs or in https://submari

Miguel 1 Oct 14, 2021
High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (w/ Redis and PostgreSQL).

fastapi-gino-arq-uvicorn High-performance Async REST API, in Python. FastAPI + GINO + Arq + Uvicorn (powered by Redis & PostgreSQL). Contents Get Star

Leo Sussan 351 Jan 04, 2023
FastAPI Project Template

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

A.Freud 4 Dec 05, 2022
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 04, 2023
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
A set of demo of deploying a Machine Learning Model in production using various methods

Machine Learning Model in Production This git is for those who have concern about serving your machine learning model to production. Overview The tuto

Vo Van Tu 53 Sep 14, 2022
A minimal Streamlit app showing how to launch and stop a FastAPI process on demand

Simple Streamlit + FastAPI Integration A minimal Streamlit app showing how to launch and stop a FastAPI process on demand. The FastAPI /run route simu

Arvindra 18 Jan 02, 2023
A Sample App to Demonstrate React Native and FastAPI Integration

React Native - Service Integration with FastAPI Backend. A Sample App to Demonstrate React Native and FastAPI Integration UI Based on NativeBase toolk

YongKi Kim 4 Nov 17, 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
Docker image with Uvicorn managed by Gunicorn for high-performance FastAPI web applications in Python 3.6 and above with performance auto-tuning. Optionally with Alpine Linux.

Supported tags and respective Dockerfile links python3.8, latest (Dockerfile) python3.7, (Dockerfile) python3.6 (Dockerfile) python3.8-slim (Dockerfil

Sebastián Ramírez 2.1k Dec 31, 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
cookiecutter template for web API with python

Python project template for Web API with cookiecutter What's this This provides the project template including minimum test/lint/typechecking package

Hitoshi Manabe 4 Jan 28, 2021
Slack webhooks API served by FastAPI

Slackers Slack webhooks API served by FastAPI What is Slackers Slackers is a FastAPI implementation to handle Slack interactions and events. It serves

Niels van Huijstee 68 Jan 05, 2023
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