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
Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks

Hook Slinger acts as a simple service that lets you send, retry, and manage event-triggered POST requests, aka webhooks. It provides a fully self-contained docker image that is easy to orchestrate, m

Redowan Delowar 96 Jan 02, 2023
Generate Class & Decorators for your FastAPI project ✨🚀

Classes and Decorators to use FastAPI with class based routing. In particular this allows you to construct an instance of a class and have methods of that instance be route handlers for FastAPI & Pyt

Yasser Tahiri 34 Oct 27, 2022
A FastAPI WebSocket application that makes use of ncellapp package by @hemantapkh

ncellFastAPI author: @awebisam Used FastAPI to create WS application. Ncellapp module by @hemantapkh NOTE: Not following best practices and, needs ref

Aashish Bhandari 7 Oct 01, 2021
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⭐

FRDP Boilerplate code for quick docker implementation of REST API with JWT Authentication using FastAPI, PostgreSQL and PgAdmin ⛏ . Getting Started Fe

BnademOverflow 53 Dec 29, 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
Instrument your FastAPI app

Prometheus FastAPI Instrumentator A configurable and modular Prometheus Instrumentator for your FastAPI. Install prometheus-fastapi-instrumentator fro

Tim Schwenke 441 Jan 05, 2023
Github timeline htmx based web app rewritten from Common Lisp to Python FastAPI

python-fastapi-github-timeline Rewrite of Common Lisp htmx app _cl-github-timeline into Python using FastAPI. This project tries to prove, that with h

Jan Vlčinský 4 Mar 25, 2022
This repository contains learning resources for Python Fast API Framework and Docker

This repository contains learning resources for Python Fast API Framework and Docker, Build High Performing Apps With Python BootCamp by Lux Academy and Data Science East Africa.

Harun Mbaabu Mwenda 23 Nov 20, 2022
REST API with FastAPI and PostgreSQL

REST API with FastAPI and PostgreSQL To have the same data in db: create table CLIENT_DATA (id SERIAL PRIMARY KEY, fullname VARCHAR(50) NOT NULL,email

Luis Quiñones Requelme 1 Nov 11, 2021
API Simples com python utilizando a biblioteca FastApi

api-fastapi-python API Simples com python utilizando a biblioteca FastApi Para rodar esse script são necessárias duas bibliotecas: Fastapi: Comando de

Leonardo Grava 0 Apr 29, 2022
FastAPI backend for Repost

Repost FastAPI This is the FastAPI implementation of the Repost API. Installation Python 3 must be installed and accessible through the use of a termi

PC 7 Jun 15, 2021
OpenAPI for Todolist RESTful API

swagger-client OpenAPI for Todolist RESTful API This Python package is automatically generated by the Swagger Codegen project: API version: 1 Package

Iko Afianando 1 Dec 19, 2021
Browse JSON API in a HTML interface.

Falcon API Browse This project provides a middleware for Falcon Web Framework that will render the response in an HTML form for documentation purpose.

Abhilash Raj 4 Mar 16, 2022
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 08, 2022
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Steve Hillier 225 Jan 05, 2023
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
Easy and secure implementation of Azure AD for your FastAPI APIs 🔒

FastAPI-Azure-auth Azure AD Authentication for FastAPI apps made easy. 🚀 Description FastAPI is a modern, fast (high-performance), web framework for

Intility 216 Dec 27, 2022
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
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 01, 2022