Pay-then-profile join desk with live card, S3 upload fallback, hydration-safe drafts; document on test9 README. Co-authored-by: Cursor <cursoragent@cursor.com>
74 lines
2.0 KiB
Python
74 lines
2.0 KiB
Python
"""Server-side Photon geocoder proxy (no browser CORS / key leakage)."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from .config import PHOTON_BASE_URL, PHOTON_TIMEOUT_SEC
|
|
|
|
log = logging.getLogger("social_svc.photon")
|
|
|
|
|
|
def _norm_feature(f: dict[str, Any]) -> dict[str, Any] | None:
|
|
props = f.get("properties") or {}
|
|
geom = f.get("geometry") or {}
|
|
coords = geom.get("coordinates") or []
|
|
if len(coords) < 2:
|
|
return None
|
|
lng, lat = float(coords[0]), float(coords[1])
|
|
name = (
|
|
props.get("name")
|
|
or props.get("city")
|
|
or props.get("town")
|
|
or props.get("village")
|
|
or props.get("county")
|
|
or ""
|
|
).strip()
|
|
if not name:
|
|
return None
|
|
country = (props.get("country") or "").strip()
|
|
state = (props.get("state") or props.get("county") or "").strip()
|
|
osm_id = props.get("osm_id")
|
|
osm_type = props.get("osm_type") or ""
|
|
cid = f"photon:{osm_type}{osm_id}" if osm_id is not None else f"photon:{lat:.4f},{lng:.4f}"
|
|
return {
|
|
"id": cid,
|
|
"name": name,
|
|
"country": country,
|
|
"state": state,
|
|
"lat": lat,
|
|
"lng": lng,
|
|
"osmKey": props.get("osm_key"),
|
|
"osmValue": props.get("osm_value"),
|
|
"source": "photon",
|
|
}
|
|
|
|
|
|
async def search_cities(q: str, *, limit: int = 8, lang: str = "zh") -> list[dict[str, Any]]:
|
|
query = (q or "").strip()
|
|
if len(query) < 2:
|
|
return []
|
|
base = (PHOTON_BASE_URL or "").rstrip("/")
|
|
if not base:
|
|
return []
|
|
url = f"{base}/api/"
|
|
params = {"q": query, "limit": max(1, min(limit, 20)), "lang": lang or "zh"}
|
|
try:
|
|
async with httpx.AsyncClient(timeout=PHOTON_TIMEOUT_SEC) as client:
|
|
res = await client.get(url, params=params)
|
|
res.raise_for_status()
|
|
data = res.json()
|
|
except Exception as exc: # pragma: no cover
|
|
log.warning("photon search failed: %s", exc)
|
|
return []
|
|
out: list[dict[str, Any]] = []
|
|
for f in data.get("features") or []:
|
|
if not isinstance(f, dict):
|
|
continue
|
|
n = _norm_feature(f)
|
|
if n:
|
|
out.append(n)
|
|
return out
|