An easy to use tool for caching fastapi returnings using sqlite as backend
- Returning json serializable data
- Using GET method
- Returning dynamic but repeated data (like data refresh everyday)
- Don't have complicated requirements and too lazy to build a tool yourself
- Returning not json serializable data (bytes, datetime, etc)
- Using POST method
- Returning frequently changing data (like data refresh every second)
- Need advanced features (recommend: fastapi-cache)
We recommend you have fastapi installed
pip install fastapi-easy-cacheThe following code will
- create a sqlite database in dbPath
- sotore cache in filesystem
import fastapi_easy_cache
fastapi_easy_cache.apiCache(db_path='./temp/cache', in_memory=False)db_path: path to sqlite database in_memory: set up cache in memory, db_path will be database name when set to True
You just need to add @cache(expire=20) under fastapi route decorator, add flil in expire time and it's all done.
expire is counted in second
from fastapi_easy_cache import cache
@app.get('/testCache/{path}')
@cache(expire=20)
def test(path):
data = path
return dataWith GET route with arguments, you must add request: Request to your function
from starlette.requests import Request
from fastapi_easy_cache import cache
@app.get('/testCacheWithArg/{path}')
@cache(expire=20)
def testArg(path, arg1, arg2, request: Request):
data = {'path': path,
'arg1': arg1,
'arg2': arg2}
return data