1- import json , redis , time
1+ import redis , time
2+ import simplejson as json
23from decimal import Decimal
34from fastapi .security import HTTPBearer
45from fastapi import Request
@@ -72,7 +73,7 @@ def set_cache(cache_key: str, data):
7273
7374 redis_client .set (
7475 cache_key ,
75- json .dumps (data , default = json_decimal ),
76+ json .dumps (data , use_decimal = True , encoding = 'utf-8' , ensure_ascii = False , default = default_serializer , allow_nan = True ),
7677 ex = config ["REDIS" ]["EXPIRY" ],
7778 )
7879
@@ -93,6 +94,39 @@ def get_cache(cache_key: str):
9394 else :
9495 return None
9596
97+ def ordinal (n ):
98+ suffix = ['th' , 'st' , 'nd' , 'rd' , 'th' ][min (n % 10 , 4 )]
99+ if 11 <= (n % 100 ) <= 13 :
100+ suffix = 'th'
101+ return str (n ) + suffix
102+
103+ def custom_date_format (dt ):
104+ day = ordinal (dt .day )
105+ month = dt .strftime ('%B' )
106+ year = dt .year
107+ time = dt .strftime ('%H:%M:%S' )
108+ return f"{ day } of { month } { year } , { time } "
109+
110+ def custom_time_format (time_value ):
111+ # Convert to Decimal for precise arithmetic
112+ time_value = Decimal (time_value )
113+
114+ # Calculate minutes and remaining seconds
115+ minutes = int (time_value // 60 )
116+ seconds = time_value % 60
117+
118+ # Format the time
119+ formatted_time = f"{ minutes } :{ seconds :06.4f} " if minutes > 0 else f"{ seconds :.4f} "
120+
121+ return formatted_time
122+
123+ def default_serializer (obj ):
124+ if isinstance (obj , datetime ):
125+ return custom_date_format (obj )
126+ elif isinstance (obj , Decimal ):
127+ return custom_time_format (obj )
128+ raise TypeError (f"Object of type { type (obj ).__name__ } is not JSON serializable" )
129+
96130
97131def json_decimal (obj ):
98132 """Convert all instances of `Decimal` to `String`
0 commit comments