Skip to content

Commit ff38a98

Browse files
Yuri ZmytrakovYuri Zmytrakov
authored andcommitted
temp
1 parent cb7ee7c commit ff38a98

File tree

2 files changed

+100
-37
lines changed

2 files changed

+100
-37
lines changed

stac_fastapi/core/stac_fastapi/core/core.py

Lines changed: 43 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@
2424
from stac_fastapi.core.base_settings import ApiBaseSettings
2525
from stac_fastapi.core.datetime_utils import format_datetime_range
2626
from stac_fastapi.core.models.links import PagingLinks
27-
from stac_fastapi.core.redis_utils import connect_redis, get_prev_link, save_self_link
27+
from stac_fastapi.core.redis_utils import (
28+
connect_redis,
29+
get_prev_link,
30+
handle_redis_pagination,
31+
save_self_link,
32+
)
2833
from stac_fastapi.core.serializers import CollectionSerializer, ItemSerializer
2934
from stac_fastapi.core.session import Session
3035
from stac_fastapi.core.utilities import filter_fields, get_bool_env
@@ -332,17 +337,6 @@ async def all_collections(
332337
current_url = str(request.url)
333338
redis_enable = get_bool_env("REDIS_ENABLE", default=False)
334339

335-
redis = None
336-
if redis_enable:
337-
try:
338-
redis = await connect_redis()
339-
logger.info("Redis connection established successfully")
340-
except Exception as e:
341-
redis = None
342-
logger.warning(
343-
f"Redis connection failed, continuing without Redis: {e}"
344-
)
345-
346340
# Convert q to a list if it's a string
347341
q_list = None
348342
if q is not None:
@@ -441,6 +435,17 @@ async def all_collections(
441435
},
442436
]
443437

438+
redis = None
439+
if redis_enable:
440+
try:
441+
redis = await connect_redis()
442+
logger.info("Redis connection established successfully")
443+
except Exception as e:
444+
redis = None
445+
logger.warning(
446+
f"Redis connection failed, continuing without Redis: {e}"
447+
)
448+
444449
if redis_enable and redis:
445450
if next_token:
446451
await save_self_link(redis, next_token, current_url)
@@ -775,7 +780,6 @@ async def post_search(
775780
HTTPException: If there is an error with the cql2_json filter.
776781
"""
777782
base_url = str(request.base_url)
778-
redis_enable = get_bool_env("REDIS_ENABLE", default=False)
779783

780784
search = self.database.make_search()
781785

@@ -900,30 +904,33 @@ async def post_search(
900904
]
901905
)
902906
links.extend(collection_links)
907+
redis_enable = get_bool_env("REDIS_ENABLE", default=False)
903908

904-
if redis_enable:
905-
redis = None
906-
try:
907-
redis = await connect_redis()
908-
logger.info("Redis connection established successfully")
909-
self_link = str(request.url)
910-
await save_self_link(redis, next_token, self_link)
911-
912-
prev_link = await get_prev_link(redis, token_param)
913-
if prev_link:
914-
links.insert(
915-
0,
916-
{
917-
"rel": "prev",
918-
"type": "application/json",
919-
"method": "GET",
920-
"href": prev_link,
921-
},
922-
)
923-
except Exception as e:
924-
logger.warning(
925-
f"Redis connection failed, continuing without Redis: {e}"
926-
)
909+
handle_redis_pagination(request, links, next_token, token_param, redis_enable)
910+
911+
# if redis_enable:
912+
# redis = None
913+
# try:
914+
# redis = await connect_redis()
915+
# logger.info("Redis connection established successfully")
916+
# self_link = str(request.url)
917+
# await save_self_link(redis, next_token, self_link)
918+
919+
# prev_link = await get_prev_link(redis, token_param)
920+
# if prev_link:
921+
# links.insert(
922+
# 0,
923+
# {
924+
# "rel": "prev",
925+
# "type": "application/json",
926+
# "method": "GET",
927+
# "href": prev_link,
928+
# },
929+
# )
930+
# except Exception as e:
931+
# logger.warning(
932+
# f"Redis connection failed, continuing without Redis: {e}"
933+
# )
927934

928935
return stac_types.ItemCollection(
929936
type="FeatureCollection",

stac_fastapi/core/stac_fastapi/core/redis_utils.py

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
"""Utilities for connecting to and managing Redis connections."""
22

3-
from typing import Optional
3+
import logging
4+
from typing import Dict, List, Optional
45

6+
from fastapi import Request
57
from pydantic_settings import BaseSettings
68
from redis import asyncio as aioredis
79
from redis.asyncio.sentinel import Sentinel
810

11+
from stac_fastapi.core.utilities import get_bool_env
12+
913
redis_pool: Optional[aioredis.Redis] = None
1014

15+
logger = logging.getLogger(__name__)
16+
1117

1218
class RedisSentinelSettings(BaseSettings):
1319
"""Configuration for connecting to Redis Sentinel."""
@@ -122,3 +128,53 @@ async def get_prev_link(redis: aioredis.Redis, token: Optional[str]) -> Optional
122128
if not token:
123129
return None
124130
return await redis.get(f"nav:self:{token}")
131+
132+
133+
async def handle_redis_pagination(
134+
request: Request,
135+
links: List[Dict],
136+
next_token: Optional[str] = None,
137+
current_token: Optional[str] = None,
138+
redis_enable: Optional[bool] = None,
139+
) -> None:
140+
"""
141+
Handle Redis-based pagination for both items and collections.
142+
143+
Args:
144+
request: FastAPI request object
145+
links: Links array to modify
146+
next_token: Token for the next page (used to save current URL)
147+
current_token: Current page token (used to retrieve previous page)
148+
redis_enable: Whether Redis is enabled (auto-detected if None)
149+
"""
150+
# Auto-detect Redis enablement if not provided
151+
if redis_enable is None:
152+
redis_enable = get_bool_env("REDIS_ENABLE", default=False)
153+
154+
if not redis_enable:
155+
return
156+
157+
try:
158+
redis = await connect_redis()
159+
logger.info("Redis connection established successfully")
160+
161+
# Save current URL for next page's previous link
162+
if next_token:
163+
self_link = str(request.url)
164+
await save_self_link(redis, next_token, self_link)
165+
166+
# Get previous page link if available
167+
if current_token:
168+
prev_link = await get_prev_link(redis, current_token)
169+
if prev_link:
170+
links.insert(
171+
0,
172+
{
173+
"rel": "prev",
174+
"type": "application/json",
175+
"method": "GET",
176+
"href": prev_link,
177+
},
178+
)
179+
except Exception as e:
180+
logger.warning(f"Redis connection failed, continuing without Redis: {e}")

0 commit comments

Comments
 (0)