From f5ec281f9dc7356b49a45a0d6b3732c4ca66c320 Mon Sep 17 00:00:00 2001 From: Russ Biggs Date: Fri, 15 Sep 2023 13:26:48 -0600 Subject: [PATCH] add redis in startup event hook --- openaq_api/openaq_api/main.py | 36 ++++++++++++++------------- openaq_api/openaq_api/routers/auth.py | 1 + 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/openaq_api/openaq_api/main.py b/openaq_api/openaq_api/main.py index aefdc4a..243778f 100644 --- a/openaq_api/openaq_api/main.py +++ b/openaq_api/openaq_api/main.py @@ -108,22 +108,6 @@ def render(self, content: Any) -> bytes: redis_client = None # initialize for generalize_schema.py -if settings.RATE_LIMITING: - logger.debug("Connecting to redis") - from redis.asyncio.cluster import RedisCluster - - try: - redis_client = RedisCluster( - host=settings.REDIS_HOST, - port=settings.REDIS_PORT, - decode_responses=True, - socket_timeout=5, - ) - app.state.redis_client = redis_client - except Exception as e: - logging.error(InfrastructureErrorLog(detail=f"failed to connect to redis: {e}")) - logger.debug("Redis connected") - app.add_middleware( CORSMiddleware, @@ -208,7 +192,24 @@ async def startup_event(): logger.debug("initializing connection pool") app.state.pool = await db_pool(None) logger.debug("Connection pool established") - + if not hasattr(app.state, "redis_client"): + if settings.RATE_LIMITING: + logger.debug("Connecting to redis") + from redis.asyncio.cluster import RedisCluster + + try: + redis_client = RedisCluster( + host=settings.REDIS_HOST, + port=settings.REDIS_PORT, + decode_responses=True, + socket_timeout=5, + ) + app.state.redis_client = redis_client + except Exception as e: + logging.error( + InfrastructureErrorLog(detail=f"failed to connect to redis: {e}") + ) + logger.debug("Redis connected") if hasattr(app.state, "counter"): app.state.counter += 1 else: @@ -245,6 +246,7 @@ def pong(): def favico(): return RedirectResponse("https://openaq.org/assets/graphics/meta/favicon.png") + # v3 app.include_router(locations.router) app.include_router(parameters.router) diff --git a/openaq_api/openaq_api/routers/auth.py b/openaq_api/openaq_api/routers/auth.py index 1cf5943..4a1ff3e 100644 --- a/openaq_api/openaq_api/routers/auth.py +++ b/openaq_api/openaq_api/routers/auth.py @@ -142,6 +142,7 @@ async def check_email(request: Request): @router.get("/verify/{verification_code}") async def verify(request: Request, verification_code: str, db: DB = Depends()): + print(f"\n\n\nAPPP: { getattr(request.app.state, 'redis_client')}\n\n") query = """ SELECT users.users_id, users.is_active, users.expires_on, entities.full_name, users.email_address