Merge branch 'master' into master

This commit is contained in:
Lucca Marques
2022-08-08 12:40:33 -03:00
committed by GitHub
18 changed files with 996 additions and 459 deletions

View File

@@ -1,15 +1,21 @@
from functools import wraps
from typing import Callable, Optional, Type
import asyncio
from functools import wraps, partial
import inspect
from typing import TYPE_CHECKING, Callable, Optional, Type
from fastapi_cache import FastAPICache
from fastapi_cache.coder import Coder
if TYPE_CHECKING:
import concurrent.futures
def cache(
expire: int = None,
coder: Type[Coder] = None,
key_builder: Callable = None,
namespace: Optional[str] = "",
executor: Optional["concurrent.futures.Executor"] = None,
):
"""
cache all function
@@ -17,6 +23,8 @@ def cache(
:param expire:
:param coder:
:param key_builder:
:param executor:
:return:
"""
@@ -29,7 +37,10 @@ def cache(
copy_kwargs = kwargs.copy()
request = copy_kwargs.pop("request", None)
response = copy_kwargs.pop("response", None)
if request and request.headers.get("Cache-Control") in ("no-store", "no-cache"):
if (
request and request.headers.get("Cache-Control") in ("no-store", "no-cache")
) or not FastAPICache.get_enable():
return await func(*args, **kwargs)
coder = coder or FastAPICache.get_coder()
@@ -61,7 +72,12 @@ def cache(
response.headers["ETag"] = etag
return coder.decode(ret)
ret = await func(*args, **kwargs)
if inspect.iscoroutinefunction(func):
ret = await func(*args, **kwargs)
else:
loop = asyncio.get_event_loop()
ret = await loop.run_in_executor(executor, partial(func, *args, **kwargs))
await backend.set(cache_key, coder.encode(ret), expire or FastAPICache.get_expire())
return ret