Skip to content

Commit

Permalink
Default to in-memory in cases redis fails to connect.
Browse files Browse the repository at this point in the history
  • Loading branch information
EvieePy committed May 5, 2024
1 parent d191db7 commit 517e151
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion starlette_plus/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@
if TYPE_CHECKING:
from starlette.types import ASGIApp, Message, Receive, Scope, Send

from .redis import Redis
from .types_.core import Methods, RouteOptions
from .types_.limiter import BucketType, ExemptCallable, RateLimitData


logger: logging.Logger = logging.getLogger(__name__)
access_logger: logging.Logger = logging.getLogger("Route")


Expand Down Expand Up @@ -183,12 +185,31 @@ def __init__(self, *args: Any, **kwargs: Unpack[ApplicationOptions]) -> None:
middleware_: list[Middleware] = kwargs.pop("middleware", [])
middleware_.insert(0, Middleware(LoggingMiddleware)) if self._access_log else None

super().__init__(*args, **kwargs, middleware=middleware_) # type: ignore
statrtups = kwargs.pop("on_startup", [])
statrtups.append(self.__startup)

super().__init__(*args, **kwargs, middleware=middleware_, on_startup=statrtups) # type: ignore

self.add_view(self)
for view in views:
self.add_view(view)

async def __startup(self) -> None:
for middleware in self.user_middleware:
redis: Redis | None = middleware.kwargs.get("redis", None) # type: ignore

if not redis:
continue

try:
resp: bool = await redis.ping()
except Exception:
resp = False

if not resp:
logger.warning("Unable to connect to redis on %s, defaulting to in-memory.", middleware.cls.__name__)
middleware.kwargs["redis"] = None

def __new__(cls, *args: Any, **kwargs: Any) -> Self:
self: Self = super().__new__(cls)
self.__routes__ = []
Expand Down

0 comments on commit 517e151

Please sign in to comment.