Description: When the Redis server is restarted or the script is flushed, and a request is made to an API endpoint that uses the Ratelimiter as a dependency, an error is thrown. This happens because the FastAPI Limiter's init function is not re-initialized after the Redis server restart, assuming that it was initialized at the time of the server restart.
The issue arises in the file fastapi_limiter/depends.py. Specifically, the exception handling in the try-except block should catch pyredis.exceptions.ResponseError, instead of pyredis.exceptions.NoScriptError, before attempting to load the Lua script.
Steps to Reproduce:
- Restart the Redis server or flush the Redis script.
- Send a request to any API endpoint where the Ratelimiter is used as a dependency.
- Observe the error: ResponseError('NOSCRIPT No matching script. Please use EVAL').
Current Behavior: The error message is caught under the assumption that NoScriptError will occur, but the correct exception type to handle is ResponseError.
Proposed Solution: In the FastAPILimiter.lua_sha loading section, change the exception type in the try-except block to catch pyredis.exceptions.ResponseError instead of pyredis.exceptions.NoScriptError before attempting to load the script. This will ensure proper exception handling when the Redis script is not available after a server restart or script flush.
File to Modify: fastapi_limiter/depends.py
try:
FastAPILimiter.lua_sha = await FastAPILimiter.redis.script_load(FastAPILimiter.lua_script)
except pyredis.exceptions.ResponseError: