File size: 1,785 Bytes
b7a7f32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from functools import wraps
import json

from starlette.responses import Response

from core.db import redis_cache_client
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from typing import Callable


def cache(timeout: int = 600) -> Callable:
    def outer_wrapper(func):
        @wraps(func)
        async def inner_wrapper(*args, **kwargs):
            identifier = f"ec_{func.__name__}_{func.__module__}"
            value = await redis_cache_client.client.get(identifier)

            if value:
                return json.loads(value)
            else:
                ret_val = await func(*args, **kwargs)
                ret_val = jsonable_encoder(ret_val)
                await redis_cache_client.client.set(identifier, json.dumps(ret_val))
                await redis_cache_client.client.expire(identifier, timeout)
                return ret_val

        return inner_wrapper

    return outer_wrapper


# TODO: Response Cache Headers

# def cache_headers(timeout: int = 600, no_cache=False, ) -> Callable:
#     def outer_wrapper(func):
#         @wraps(func)
#         async def inner_wrapper(*args, **kwargs):
#             print(func.__module__)
#             identifier = f"ec_{func.__name__}_{func.__module__}"
#             value = await redis_cache_client.client.get(identifier)

#             if value:
#                 return json.loads(value)
#             else:
#                 ret_val = await func(*args, **kwargs)
#                 ret_val = jsonable_encoder(ret_val)
#                 await redis_cache_client.client.set(identifier, json.dumps(ret_val))
#                 await redis_cache_client.client.expire(identifier, timeout)
#                 return ret_val

#         return inner_wrapper

#     return outer_wrapper