fastapi-cache icon indicating copy to clipboard operation
fastapi-cache copied to clipboard

[question] how to cache 200 http responses only?

Open PieroValdebenito opened this issue 2 years ago • 2 comments

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.

PieroValdebenito avatar Nov 12 '21 16:11 PieroValdebenito

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,
    }

PieroValdebenito avatar Nov 12 '21 17:11 PieroValdebenito

Try raise HTTPException(status=500)

long2ice avatar Nov 13 '21 00:11 long2ice

Try raise HTTPException(status=500)

Can this return specific data?

mkdir700 avatar Nov 08 '22 14:11 mkdir700

Yes, you can raise any exception with any data

long2ice avatar Nov 08 '22 14:11 long2ice

thanks. i got it. https://fastapi.tiangolo.com/tutorial/handling-errors/?h=httpexception#install-custom-exception-handlers

mkdir700 avatar Nov 08 '22 14:11 mkdir700