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
Simple FastAPI Example : Blog API using FastAPI : Beginner Friendly

fastapi_blog FastAPI : Simple Blog API with CRUD operation Steps to run the project: git clone https://github.com/mrAvi07/fastapi_blog.git cd fastapi-

Avinash Alanjkar 1 Oct 8, 2022
Cache-house - Caching tool for python, working with Redis single instance and Redis cluster mode

Caching tool for python, working with Redis single instance and Redis cluster mo

Tural 14 Jan 6, 2022
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.

Project generator and manager for FastAPI. Source Code: View it on Github Features ?? Creates customizable project boilerplate. Creates customizable a

Yagiz Degirmenci 1k Jan 2, 2023
Пример использования GraphQL Ariadne с FastAPI и сравнение его с GraphQL Graphene FastAPI

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

ZeBrains Team 9 Nov 10, 2022
Sample-fastapi - A sample app using Fastapi that you can deploy on App Platform

Getting Started We provide a sample app using Fastapi that you can deploy on App

Erhan BÜTE 2 Jan 17, 2022
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 1, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 2022
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

Glib 14 Dec 5, 2022
Code Specialist 27 Oct 16, 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
FastAPI-Amis-Admin is a high-performance, efficient and easily extensible FastAPI admin framework. Inspired by django-admin, and has as many powerful functions as django-admin.

简体中文 | English 项目介绍 FastAPI-Amis-Admin fastapi-amis-admin是一个拥有高性能,高效率,易拓展的fastapi管理后台框架. 启发自Django-Admin,并且拥有不逊色于Django-Admin的强大功能. 源码 · 在线演示 · 文档 · 文

AmisAdmin 318 Dec 31, 2022
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

Michael Freeborn 465 Jan 7, 2023
🐍 Simple FastAPI template with factory pattern architecture

Description This is a minimalistic and extensible FastAPI template that incorporates factory pattern architecture with divisional folder structure. It

Redowan Delowar 551 Dec 24, 2022
FastAPI native extension, easy and simple JWT auth

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

Konstantin Chernyshev 19 Dec 12, 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
A dynamic FastAPI router that automatically creates CRUD routes for your models

⚡ Create CRUD routes with lighting speed ⚡ A dynamic FastAPI router that automatically creates CRUD routes for your models

Adam Watkins 950 Jan 8, 2023
Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

identix.one 543 Jan 5, 2023
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 4, 2023
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 5, 2023