|
2 | 2 |
|
3 | 3 | import json |
4 | 4 | import logging |
| 5 | +from contextlib import asynccontextmanager |
5 | 6 | from typing import List, Optional, Tuple |
6 | 7 |
|
7 | 8 | from pydantic import field_validator |
@@ -237,31 +238,44 @@ async def get_prev_link(redis: aioredis.Redis, token: Optional[str]) -> Optional |
237 | 238 | return await redis.get(f"nav:self:{token}") |
238 | 239 |
|
239 | 240 |
|
240 | | -async def redis_pagination_links( |
241 | | - current_url: str, token: str, next_token: str, links: list |
242 | | -) -> None: |
243 | | - """Handle Redis pagination.""" |
| 241 | +@asynccontextmanager |
| 242 | +async def redis_connection(): |
| 243 | + """Async context manager for Redis connections.""" |
244 | 244 | redis = await connect_redis() |
245 | 245 | if not redis: |
246 | 246 | logger.warning("Redis connection failed.") |
| 247 | + yield None |
247 | 248 | return |
248 | | - |
249 | 249 | try: |
250 | | - if next_token: |
251 | | - await save_self_link(redis, next_token, current_url) |
252 | | - |
253 | | - prev_link = await get_prev_link(redis, token) |
254 | | - if prev_link: |
255 | | - links.insert( |
256 | | - 0, |
257 | | - { |
258 | | - "rel": "prev", |
259 | | - "type": "application/json", |
260 | | - "method": "GET", |
261 | | - "href": prev_link, |
262 | | - }, |
263 | | - ) |
264 | | - except Exception as e: |
265 | | - logger.warning(f"Redis pagination operation failed: {e}") |
| 250 | + yield redis |
266 | 251 | finally: |
267 | 252 | await redis.close() |
| 253 | + |
| 254 | + |
| 255 | +async def redis_pagination_links( |
| 256 | + current_url: str, token: str, next_token: str, links: list |
| 257 | +) -> None: |
| 258 | + """Handle Redis pagination.""" |
| 259 | + async with redis_connection() as redis: |
| 260 | + # redis = await connect_redis() |
| 261 | + if not redis: |
| 262 | + logger.warning("Redis connection failed.") |
| 263 | + return |
| 264 | + |
| 265 | + try: |
| 266 | + if next_token: |
| 267 | + await save_self_link(redis, next_token, current_url) |
| 268 | + |
| 269 | + prev_link = await get_prev_link(redis, token) |
| 270 | + if prev_link: |
| 271 | + links.insert( |
| 272 | + 0, |
| 273 | + { |
| 274 | + "rel": "prev", |
| 275 | + "type": "application/json", |
| 276 | + "method": "GET", |
| 277 | + "href": prev_link, |
| 278 | + }, |
| 279 | + ) |
| 280 | + except Exception as e: |
| 281 | + logger.warning(f"Redis pagination operation failed: {e}") |
0 commit comments