即席查询取工参属性,OpenCode 导出当天全市 CGI 和经纬度,按 CGI 合并后存成快照;即席查询失败或 CGI 对不上时改由 OpenCode 一并导出属性。拆除前后的工参日期按库优先、逐月回溯的规则选取,多个任务取同一天时只取一次。即席查询 getTableCount 出错不再被当成 0 行。
413 lines
16 KiB
Python
413 lines
16 KiB
Python
"""即席查询的分类、表和按相对时间取数。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import json
|
||
import re
|
||
from datetime import date, datetime, timedelta
|
||
from urllib.parse import urlencode
|
||
|
||
import httpx
|
||
|
||
from app.nqi.client import NqiAuthError, NqiClient, NqiError, _landed_on_login
|
||
from app.nqi.constants import ORIGIN
|
||
|
||
ADHOC = f"{ORIGIN}/pro-adhoc"
|
||
PAGE = f"{ADHOC}/adhocquery"
|
||
ENTRY = f"{ADHOC}/index"
|
||
PAGE_SIZE = 200
|
||
MAX_PAGES = 2000
|
||
TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"}
|
||
|
||
|
||
def time_window(mode: str, count: int, today: date) -> tuple[datetime, datetime]:
|
||
if mode not in TIME_MODES:
|
||
raise ValueError("数据时间不正确")
|
||
amount = 1 if mode in {"prev_month", "prev_week", "prev_day"} else count
|
||
if amount < 1 or amount > 366:
|
||
raise ValueError("时间数量需要在 1 到 366 之间")
|
||
if mode in {"prev_month", "prev_months"}:
|
||
start_month = _shift_month(today.replace(day=1), -amount)
|
||
end = today.replace(day=1) - timedelta(days=1)
|
||
start = start_month
|
||
elif mode in {"prev_week", "prev_weeks"}:
|
||
this_monday = today - timedelta(days=today.weekday())
|
||
end = this_monday - timedelta(days=1)
|
||
start = this_monday - timedelta(weeks=amount)
|
||
else:
|
||
end = today - timedelta(days=1)
|
||
start = today - timedelta(days=amount)
|
||
return _start(start), _end(end)
|
||
|
||
|
||
def _shift_month(first: date, offset: int) -> date:
|
||
month_index = first.year * 12 + (first.month - 1) + offset
|
||
year, month = divmod(month_index, 12)
|
||
return date(year, month + 1, 1)
|
||
|
||
|
||
def _start(day: date) -> datetime:
|
||
return datetime(day.year, day.month, day.day)
|
||
|
||
|
||
def _end(day: date) -> datetime:
|
||
return datetime(day.year, day.month, day.day, 23, 59, 59)
|
||
|
||
|
||
async def ensure_session(client: NqiClient) -> None:
|
||
"""单点入口是 /pro-adhoc/index。票据有效时,这里会换成即席查询自己的会话。"""
|
||
response = await client._request(
|
||
"GET",
|
||
ENTRY,
|
||
headers={
|
||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||
"Referer": f"{ORIGIN}/pro-portal/",
|
||
"Upgrade-Insecure-Requests": "1",
|
||
},
|
||
check_auth=False,
|
||
)
|
||
if response.status_code >= 400 or _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):
|
||
raise NqiError("没有取到查询分类")
|
||
result = []
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
code = row.get("code")
|
||
name = str(row.get("name_cn") or "").strip()
|
||
if code is None or not name:
|
||
continue
|
||
result.append({"code": int(code), "name": name})
|
||
result.sort(key=lambda item: item["code"])
|
||
return result
|
||
|
||
|
||
async def catalog_tree(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):
|
||
raise NqiError("没有取到查询分类")
|
||
groups = []
|
||
for row in rows:
|
||
if not isinstance(row, dict) or row.get("code") is None:
|
||
continue
|
||
name = str(row.get("name_cn") or "").strip()
|
||
if not name:
|
||
continue
|
||
code = int(row["code"])
|
||
menu = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
|
||
groups.append({"code": code, "name": name, "tables": _table_rows(menu)})
|
||
groups.sort(key=lambda item: item["code"])
|
||
return groups
|
||
|
||
|
||
def _table_rows(payload: object) -> list[dict]:
|
||
if not isinstance(payload, list):
|
||
return []
|
||
result = []
|
||
for row in payload:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
tablename = str(row.get("tablename") or "").strip()
|
||
title = str(row.get("tablename_cn") or tablename).strip()
|
||
if tablename:
|
||
result.append({"tablename": tablename, "name": title})
|
||
return result
|
||
|
||
|
||
async def tables(client: NqiClient, code: int) -> list[dict]:
|
||
await ensure_session(client)
|
||
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
|
||
result = _table_rows(payload)
|
||
if not isinstance(payload, list):
|
||
raise NqiError("没有取到这个分类下的表")
|
||
return result
|
||
|
||
|
||
async def export_table(
|
||
client: NqiClient,
|
||
tablename: str,
|
||
start: datetime,
|
||
end: datetime,
|
||
city: str,
|
||
) -> tuple[str, list[dict], list[dict]]:
|
||
await ensure_session(client)
|
||
columns = await _columns(client, tablename)
|
||
if not columns:
|
||
raise NqiError("这张表没有可导出的字段")
|
||
title = str(columns[0].get("tablename_cn") or tablename)
|
||
selected = [_field(column) for column in columns]
|
||
where = _where(columns[0], start, end, city)
|
||
common = {
|
||
"geographicdimension": columns[0].get("geographicdimension") or "",
|
||
"timedimension": columns[0].get("timedimension") or "",
|
||
"enodebField": columns[0].get("enodeb_field") or "",
|
||
"cgiField": columns[0].get("cgi_field") or "",
|
||
"timeField": columns[0].get("time_field") or "starttime",
|
||
"cellField": columns[0].get("cell_field") or "",
|
||
"cityField": columns[0].get("city_field") or "city",
|
||
"result": json.dumps({"result": selected}, ensure_ascii=False),
|
||
"where": json.dumps(where, ensure_ascii=False),
|
||
}
|
||
total, index_count = await _count(client, common)
|
||
rows: list[dict] = []
|
||
start_at = 0
|
||
pages = 0
|
||
while start_at < total:
|
||
pages += 1
|
||
if pages > MAX_PAGES:
|
||
raise NqiError("数据行数超出单次导出上限")
|
||
page = await _post_json(
|
||
client,
|
||
f"{PAGE}/getTable",
|
||
{
|
||
**common,
|
||
**_column_form(columns),
|
||
"draw": pages,
|
||
"start": start_at,
|
||
"length": PAGE_SIZE,
|
||
"indexcount": index_count,
|
||
"total": total,
|
||
"order[0][column]": 0,
|
||
"order[0][dir]": "desc",
|
||
"search[value]": "",
|
||
"search[regex]": "false",
|
||
},
|
||
)
|
||
data = page.get("data") if isinstance(page, dict) else None
|
||
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
|
||
rows.extend(batch)
|
||
if len(batch) < PAGE_SIZE:
|
||
break
|
||
start_at += PAGE_SIZE
|
||
return title, columns, rows
|
||
|
||
|
||
async def export_day(
|
||
client: NqiClient,
|
||
tablename: str,
|
||
day: date,
|
||
city: str,
|
||
fields: tuple[str, ...],
|
||
*,
|
||
page_size: int = PAGE_SIZE,
|
||
pause_seconds: float = 0.3,
|
||
) -> list[dict]:
|
||
"""取一张表某一天、某个地市的指定几列。
|
||
|
||
维度有多个可选值时(如“小区,网格,地市,分公司”“天粒度”),按页面默认取第一个并去掉“粒度”。
|
||
翻页按实际返回的行数推进,平台把每页压到更少时也不会漏行;取不全就报错。
|
||
"""
|
||
await ensure_session(client)
|
||
columns = await _columns(client, tablename)
|
||
selected = [column for column in columns if column.get("columnname") in fields]
|
||
missing = set(fields) - {str(column.get("columnname")) for column in selected}
|
||
if missing:
|
||
raise NqiError(f"{tablename} 缺少字段:{'、'.join(sorted(missing))}")
|
||
head = columns[0]
|
||
common = {
|
||
"geographicdimension": _first_choice(head.get("geographicdimension")),
|
||
"timedimension": _first_choice(head.get("timedimension")).removesuffix("粒度"),
|
||
"enodebField": head.get("enodeb_field") or "",
|
||
"cgiField": head.get("cgi_field") or "",
|
||
"timeField": head.get("time_field") or "starttime",
|
||
"cellField": head.get("cell_field") or "",
|
||
"cityField": head.get("city_field") or "city",
|
||
"result": json.dumps({"result": [_field(column) for column in selected]}, ensure_ascii=False),
|
||
"where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False),
|
||
}
|
||
total, index_count = await _count(client, common)
|
||
rows: list[dict] = []
|
||
pages = 0
|
||
while len(rows) < total:
|
||
pages += 1
|
||
if pages > MAX_PAGES:
|
||
raise NqiError("数据行数超出单次导出上限")
|
||
page = await _post_json(
|
||
client,
|
||
f"{PAGE}/getTable",
|
||
{
|
||
**common,
|
||
**_column_form(selected),
|
||
"draw": pages,
|
||
"start": len(rows),
|
||
"length": page_size,
|
||
"indexcount": index_count,
|
||
"total": total,
|
||
"order[0][column]": 0,
|
||
"order[0][dir]": "desc",
|
||
"search[value]": "",
|
||
"search[regex]": "false",
|
||
},
|
||
)
|
||
data = page.get("data") if isinstance(page, dict) else None
|
||
batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
|
||
if not batch:
|
||
break
|
||
rows.extend(batch)
|
||
if pause_seconds:
|
||
await asyncio.sleep(pause_seconds)
|
||
if len(rows) < total:
|
||
raise NqiError(f"{tablename} 只取到 {len(rows)} 行,应有 {total} 行")
|
||
return rows
|
||
|
||
|
||
def _first_choice(value: object) -> str:
|
||
return re.split(r"[,,.、]", str(value or ""))[0].strip()
|
||
|
||
|
||
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
|
||
"""平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。"""
|
||
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
|
||
if not isinstance(counted, dict) or "count" not in counted:
|
||
message = counted.get("message") if isinstance(counted, dict) else ""
|
||
raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}")
|
||
return int(counted.get("count") or 0), str(counted.get("indexcount") or "0")
|
||
|
||
|
||
def _field(column: dict) -> dict:
|
||
return {
|
||
"feildtype": column.get("fieldtype") or "",
|
||
"table": column.get("tablename") or "",
|
||
"tableName": column.get("tablename_cn") or "",
|
||
"datatype": column.get("datatype") or "",
|
||
"columntype": str(column.get("columntype") if column.get("columntype") is not None else ""),
|
||
"feildName": column.get("columnname_cn") or "",
|
||
"feild": column.get("columnname") or "",
|
||
"poly": "无",
|
||
"anyWay": "无",
|
||
"chart": "无",
|
||
"chartpoly": "无",
|
||
}
|
||
|
||
|
||
def _where(column: dict, start: datetime, end: datetime, city: str) -> list[dict]:
|
||
time_field = str(column.get("time_field") or "starttime")
|
||
conditions = [
|
||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": ">=", "val": _stamp(start), "whereCon": "and", "query": True},
|
||
{"datatype": "timestamp", "feild": time_field, "feildName": "", "symbol": "<", "val": _stamp(end), "whereCon": "and", "query": True},
|
||
]
|
||
city_name = city.strip()
|
||
if city_name:
|
||
conditions.append(
|
||
{
|
||
"datatype": "character",
|
||
"feild": str(column.get("city_field") or "city"),
|
||
"feildName": "",
|
||
"symbol": "in",
|
||
"val": city_name,
|
||
"whereCon": "and",
|
||
"query": True,
|
||
}
|
||
)
|
||
return conditions
|
||
|
||
|
||
def _stamp(value: datetime) -> str:
|
||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
def _column_form(columns: list[dict]) -> dict:
|
||
form: dict[str, str] = {}
|
||
for index, column in enumerate(columns):
|
||
prefix = f"columns[{index}]"
|
||
form[f"{prefix}[data]"] = str(column.get("columnname") or "")
|
||
form[f"{prefix}[name]"] = ""
|
||
form[f"{prefix}[searchable]"] = "true"
|
||
form[f"{prefix}[orderable]"] = "true"
|
||
form[f"{prefix}[search][value]"] = ""
|
||
form[f"{prefix}[search][regex]"] = "false"
|
||
return form
|
||
|
||
|
||
async def search_by_field(client: NqiClient, keyword: str) -> list[dict]:
|
||
"""按字段中文名、英文名或字段分类,找出包含它的表。"""
|
||
text = keyword.strip()
|
||
if not text or len(text) > 80 or any(ord(char) < 32 for char in text):
|
||
raise ValueError("请输入字段名称")
|
||
await ensure_session(client)
|
||
payload = await _post_json(
|
||
client,
|
||
f"{PAGE}/search",
|
||
{"key": text, "field": ["columnname_cn", "columnname", "fieldtype"]},
|
||
)
|
||
rows = payload.get("CFG_ADHOC_CONF_SEARCH") if isinstance(payload, dict) else None
|
||
if not isinstance(rows, list):
|
||
raise NqiError("没有查到相关的表")
|
||
grouped: dict[str, dict] = {}
|
||
order: list[str] = []
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
tablename = str(row.get("tablename") or "").strip()
|
||
field_name = str(row.get("columnname_cn") or row.get("columnname") or "").strip()
|
||
if not tablename or not field_name:
|
||
continue
|
||
item = grouped.get(tablename)
|
||
if item is None:
|
||
title = str(row.get("tablename_cn") or tablename).strip() or tablename
|
||
item = {"tablename": tablename, "name": title, "fields": []}
|
||
grouped[tablename] = item
|
||
order.append(tablename)
|
||
column = str(row.get("columnname") or "").strip()
|
||
if any(existing["column"] == column and existing["name"] == field_name for existing in item["fields"]):
|
||
continue
|
||
item["fields"].append({"name": field_name, "column": column, "type": str(row.get("datatype") or "").strip()})
|
||
return [grouped[name] for name in order]
|
||
|
||
|
||
async def table_fields(client: NqiClient, tablename: str) -> list[dict]:
|
||
await ensure_session(client)
|
||
rows = await _columns(client, tablename)
|
||
fields = []
|
||
for row in rows:
|
||
name = str(row.get("columnname_cn") or row.get("columnname") or "").strip()
|
||
if not name:
|
||
continue
|
||
fields.append({"name": name, "type": str(row.get("datatype") or "").strip()})
|
||
return fields
|
||
|
||
|
||
async def _columns(client: NqiClient, tablename: str) -> list[dict]:
|
||
payload = await _post_json(client, f"{PAGE}/getSelectTable", {"tablename": tablename})
|
||
rows = payload.get("CFG_ADHOC_CONF_TABLE") if isinstance(payload, dict) else None
|
||
if not isinstance(rows, list):
|
||
raise NqiError("没有取到表字段")
|
||
shown = [row for row in rows if isinstance(row, dict) and str(row.get("isshow")) == "1" and row.get("columnname")]
|
||
usable = shown or [row for row in rows if isinstance(row, dict) and row.get("columnname")]
|
||
usable.sort(key=lambda row: int(row.get("sort") or 0))
|
||
return usable
|
||
|
||
|
||
async def _post_json(client: NqiClient, url: str, form: dict) -> dict | list:
|
||
response = await client._request(
|
||
"POST",
|
||
url,
|
||
content=urlencode(form, doseq=True).encode("utf-8"),
|
||
headers={
|
||
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
||
"Origin": ORIGIN,
|
||
"Referer": PAGE,
|
||
"X-Requested-With": "XMLHttpRequest",
|
||
},
|
||
timeout=httpx.Timeout(120.0, connect=15.0),
|
||
)
|
||
if response.status_code >= 400:
|
||
raise NqiError("查询没有返回数据")
|
||
try:
|
||
payload = response.json()
|
||
except json.JSONDecodeError as exc:
|
||
raise NqiError("查询返回的内容无法识别") from exc
|
||
if not isinstance(payload, (dict, list)):
|
||
raise NqiError("查询返回的内容无法识别")
|
||
return payload
|