fastapi-cache
fastapi-cache copied to clipboard
[question] how to cache 200 http responses only?
I'm not sure how to discard 500 and 400 errors from cache using InMemoryBackend. My usecase depends on an external provider, but I want to cache only success responses. If the provider fails I want to keep asking for the data. I tried to inject 'no-cache' header but request headers are inmutable.
Example
@app.get("/data")
@cache(expire=3600)
async def get_data_handler(request: Request):
data = get_data_from_provider()
if 'error' in data:
# do not cache this response
return JSONResponse(data, status_code=500)
return {
'last_update': datetime.now().astimezone(),
**data,
}
Try raise HTTPException(status=500)
Try
raise HTTPException(status=500)
Can this return specific data?
Yes, you can raise any exception with any data
thanks. i got it. https://fastapi.tiangolo.com/tutorial/handling-errors/?h=httpexception#install-custom-exception-handlers