diff --git a/backend/app/api/http.py b/backend/app/api/http.py index cd13737..be98aa9 100644 --- a/backend/app/api/http.py +++ b/backend/app/api/http.py @@ -477,9 +477,12 @@ def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), try: client.import_cookies(cookies) await client.current_user() - if code is None: - return {"categories": await categories(client)} - return {"tables": await tables(client, code)} + try: + if code is None: + return {"categories": await categories(client)} + return {"tables": await tables(client, code)} + except NqiAuthError as exc: + raise NqiError("门户登录还在,但进入即席查询没有接上,请用这个大数据账号重新登录一次") from exc finally: await client.aclose() diff --git a/backend/app/nqi/adhoc.py b/backend/app/nqi/adhoc.py index 9860767..1f0636e 100644 --- a/backend/app/nqi/adhoc.py +++ b/backend/app/nqi/adhoc.py @@ -10,7 +10,7 @@ from urllib.parse import urlencode import httpx -from app.nqi.client import NqiClient, NqiError +from app.nqi.client import NqiAuthError, NqiClient, NqiError, _landed_on_login from app.nqi.constants import ORIGIN ADHOC = f"{ORIGIN}/pro-adhoc" @@ -54,7 +54,20 @@ def _end(day: date) -> datetime: return datetime(day.year, day.month, day.day, 23, 59, 59) +async def ensure_session(client: NqiClient) -> None: + """门户凭证有效时,还要先打开即席查询,才会拿到这个应用自己的会话。""" + response = await client._request( + "GET", + PAGE, + headers={"Referer": f"{ORIGIN}/pro-portal/"}, + check_auth=False, + ) + if _landed_on_login(response): + raise NqiAuthError("登录已失效,请重新登录") + + async def categories(client: NqiClient) -> list[dict]: + await ensure_session(client) payload = await _post_json(client, f"{ADHOC}/index/searchTableType", {}) rows = payload.get("CFG_ADHOC_CODE") if isinstance(payload, dict) else None if not isinstance(rows, list): @@ -73,6 +86,7 @@ async def categories(client: NqiClient) -> list[dict]: async def tables(client: NqiClient, code: int) -> list[dict]: + await ensure_session(client) payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code}) if not isinstance(payload, list): raise NqiError("没有取到这个分类下的表") @@ -94,6 +108,7 @@ async def export_table( end: datetime, city: str, ) -> tuple[str, bytes, int]: + await ensure_session(client) columns = await _columns(client, tablename) if not columns: raise NqiError("这张表没有可导出的字段")