Skip to content

Instantly share code, notes, and snippets.

@euri10
Created March 10, 2020 13:37
Show Gist options
  • Save euri10/9b65b357b94da110aec5cdbfef7a9d17 to your computer and use it in GitHub Desktop.
Save euri10/9b65b357b94da110aec5cdbfef7a9d17 to your computer and use it in GitHub Desktop.
import asyncio
import logging
import time
from functools import lru_cache
import uvicorn
from aiocache import cached
from fastapi import FastAPI, APIRouter, Depends
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
class GetCachedSomething:
def __init__(self, value: str):
self.value = value
@lru_cache
def sync_load(self) -> str:
logger.debug("loaded")
response = self.value + "_sync"
time.sleep(1)
logger.debug("out loaded")
return response
@cached()
async def async_load(self) -> str:
logger.debug("async loaded")
response = self.value + "_async"
await asyncio.sleep(1)
logger.debug("out async loaded")
return response
app = FastAPI()
users_router = APIRouter()
get_users_something = GetCachedSomething("users.sql")
@users_router.get("/asyncload")
async def asyncload(users_queries=Depends(get_users_something.async_load)):
return users_queries
@users_router.get("/syncload")
def syncload(users_queries=Depends(get_users_something.sync_load)):
return users_queries
app.include_router(users_router)
if __name__ == "__main__":
uvicorn.run("fastapi_depends_singleton:app", reload=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment