better caching

This commit is contained in:
MuslemRahimi 2024-07-12 14:55:40 +02:00
parent 3668a5ac19
commit ca9b940d9c
2 changed files with 23 additions and 8 deletions

View File

@ -2677,16 +2677,30 @@ async def get_price_analysis(data:TickerData):
cache_key = f"price-analysis-{ticker}" cache_key = f"price-analysis-{ticker}"
cached_result = redis_client.get(cache_key) cached_result = redis_client.get(cache_key)
if cached_result: if cached_result:
return ujson.loads(cached_result) return StreamingResponse(
io.BytesIO(cached_result),
media_type="application/json",
headers={"Content-Encoding": "gzip"}
)
try: try:
with open(f"json/price-analysis/{ticker}.json", 'r') as file: with open(f"json/price-analysis/{ticker}.json", 'r') as file:
res = ujson.load(file) res = ujson.load(file)
except: except:
res = {} res = {}
redis_client.set(cache_key, ujson.dumps(res)) data = ujson.dumps(res).encode('utf-8')
compressed_data = gzip.compress(data)
redis_client.set(cache_key, compressed_data)
redis_client.expire(cache_key, 3600*3600) # Set cache expiration time to 1 day redis_client.expire(cache_key, 3600*3600) # Set cache expiration time to 1 day
return res
return StreamingResponse(
io.BytesIO(compressed_data),
media_type="application/json",
headers={"Content-Encoding": "gzip"}
)
@app.post("/fundamental-predictor-analysis") @app.post("/fundamental-predictor-analysis")
async def get_fundamental_predictor_analysis(data:TickerData): async def get_fundamental_predictor_analysis(data:TickerData):
@ -2825,7 +2839,7 @@ async def get_politician_stats(data:PoliticianId):
@app.get("/all-politicians") @app.get("/all-politicians")
async def get_all_politician(): async def get_all_politician():
'''
cache_key = f"all-politician" cache_key = f"all-politician"
cached_result = redis_client.get(cache_key) cached_result = redis_client.get(cache_key)
if cached_result: if cached_result:
@ -2834,7 +2848,7 @@ async def get_all_politician():
media_type="application/json", media_type="application/json",
headers={"Content-Encoding": "gzip"} headers={"Content-Encoding": "gzip"}
) )
'''
try: try:
with open(f"json/congress-trading/search_list.json", 'r') as file: with open(f"json/congress-trading/search_list.json", 'r') as file:
@ -2845,8 +2859,8 @@ async def get_all_politician():
data = ujson.dumps(res_list).encode('utf-8') data = ujson.dumps(res_list).encode('utf-8')
compressed_data = gzip.compress(data) compressed_data = gzip.compress(data)
#redis_client.set(cache_key, compressed_data) redis_client.set(cache_key, compressed_data)
#redis_client.expire(cache_key, 3600*3600) # Set cache expiration time to 1 day redis_client.expire(cache_key, 3600*3600) # Set cache expiration time to 1 day
return StreamingResponse( return StreamingResponse(
io.BytesIO(compressed_data), io.BytesIO(compressed_data),

View File

@ -35,3 +35,4 @@ ujson
faker faker
finnhub-python finnhub-python
intrinio_sdk intrinio_sdk
openai