290 lines
10 KiB
Python
290 lines
10 KiB
Python
"""即席查询的分类、表和按相对时间取数。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
import io
|
|
import json
|
|
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"
|
|
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:
|
|
"""门户凭证有效时,还要先打开即席查询,才会拿到这个应用自己的会话。"""
|
|
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):
|
|
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, bytes, int]:
|
|
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),
|
|
}
|
|
counted = await _post_json(client, f"{PAGE}/getTableCount", common)
|
|
total = int(counted.get("count") or 0) if isinstance(counted, dict) else 0
|
|
index_count = str(counted.get("indexcount") or "0") if isinstance(counted, dict) else "0"
|
|
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, _csv(columns, rows), len(rows)
|
|
|
|
|
|
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
|
|
|
|
|
|
def _csv(columns: list[dict], rows: list[dict]) -> bytes:
|
|
buffer = io.StringIO()
|
|
writer = csv.writer(buffer)
|
|
writer.writerow([str(column.get("columnname_cn") or column.get("columnname") or "") for column in columns])
|
|
keys = [str(column.get("columnname") or "") for column in columns]
|
|
for row in rows:
|
|
writer.writerow(["" if row.get(key) is None else row.get(key) for key in keys])
|
|
return buffer.getvalue().encode("utf-8-sig")
|
|
|
|
|
|
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
|