import hashlib import httpx from fastapi import APIRouter, Query, Request from app.core.config import settings router = APIRouter() CACHE_TTL = 3600 def _cache_key(prefix: str, **kwargs: str) -> str: raw = "&".join(f"{k}={v}" for k, v in sorted(kwargs.items()) if v) return f"map:{prefix}:{hashlib.md5(raw.encode()).hexdigest()}" @router.get("/geocoder/reverse") async def reverse_geocode( request: Request, location: str = Query(..., description="lat,lng"), ): redis = request.app.state.redis ck = _cache_key("rev", location=location) if redis: cached = await redis.get(ck) if cached: import json return json.loads(cached) async with httpx.AsyncClient(timeout=5) as client: resp = await client.get( "https://apis.map.qq.com/ws/geocoder/v1/", params={ "location": location, "key": settings.TENCENT_MAP_KEY, "get_poi": 1, }, ) data = resp.json() if redis and data.get("status") == 0: import json await redis.set(ck, json.dumps(data), ex=CACHE_TTL) return data @router.get("/place/search") async def place_search( request: Request, keyword: str = Query(...), boundary: str = Query(...), ): redis = request.app.state.redis ck = _cache_key("place", keyword=keyword, boundary=boundary) if redis: cached = await redis.get(ck) if cached: import json return json.loads(cached) async with httpx.AsyncClient(timeout=5) as client: resp = await client.get( "https://apis.map.qq.com/ws/place/v1/search", params={ "keyword": keyword, "boundary": boundary, "page_size": 10, "page_index": 1, "key": settings.TENCENT_MAP_KEY, }, ) data = resp.json() if redis and data.get("status") == 0: import json await redis.set(ck, json.dumps(data), ex=CACHE_TTL) return data