feat: 采集任务可按即席查询分类选表,并按相对时间导出 CSV
This commit is contained in:
+71
-1
@@ -1,7 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.responses import Response
|
||||
@@ -14,6 +15,7 @@ from app.config import env_database, hosted, installed, result_dir
|
||||
from app.install import InstallError, perform_install
|
||||
from app.db import get_session, session_scope
|
||||
from app.models import AppSetting, CollectionSource, ExportTask, NqiAccount, User, utcnow
|
||||
from app.nqi.adhoc import TIME_MODES, categories, tables, time_window
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.nqi.flows import drop, purge, remember, take
|
||||
from app.security import hash_password, issue_token, verify_password
|
||||
@@ -465,6 +467,38 @@ def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/admin/nqi/catalog")
|
||||
def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
cookies = _pool_cookies(session)
|
||||
|
||||
async def run() -> dict:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
await client.current_user()
|
||||
if code is None:
|
||||
return {"categories": await categories(client)}
|
||||
return {"tables": await tables(client, code)}
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
try:
|
||||
return asyncio.run(run())
|
||||
except NqiAuthError as exc:
|
||||
raise _bad("账号池凭证已失效") from exc
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
|
||||
|
||||
def _pool_cookies(session: Session) -> list:
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc()))
|
||||
cookies = list(account.cookies or []) if account is not None else []
|
||||
if not cookies:
|
||||
raise _bad("账号池里没有可用凭证")
|
||||
return cookies
|
||||
|
||||
|
||||
@router.get("/admin/sources")
|
||||
def list_sources(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
@@ -522,9 +556,45 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
|
||||
current = dict(source.config or {})
|
||||
if not incoming.get("password"):
|
||||
incoming["password"] = current.get("password") or ""
|
||||
if source.kind == "nqi" and "tables" in incoming:
|
||||
incoming = _nqi_tables(incoming)
|
||||
source.config = incoming
|
||||
|
||||
|
||||
def _nqi_tables(config: dict) -> dict:
|
||||
raw = config.get("tables")
|
||||
if not isinstance(raw, list) or not raw or len(raw) > 30:
|
||||
raise _bad("请选择要采集的表")
|
||||
cleaned = []
|
||||
for item in raw:
|
||||
if not isinstance(item, dict):
|
||||
raise _bad("请选择要采集的表")
|
||||
tablename = str(item.get("tablename") or "").strip()
|
||||
name = str(item.get("name") or tablename).strip()
|
||||
if not tablename or len(tablename) > 180 or len(name) > 120:
|
||||
raise _bad("请选择要采集的表")
|
||||
try:
|
||||
code = int(item.get("code") or 0)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("请选择要采集的表") from exc
|
||||
cleaned.append({"code": code, "category": str(item.get("category") or "")[:80], "tablename": tablename, "name": name})
|
||||
mode = str(config.get("timeMode") or "")
|
||||
if mode not in TIME_MODES:
|
||||
raise _bad("数据时间不正确")
|
||||
try:
|
||||
count = int(config.get("timeCount") or 1)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("时间数量不正确") from exc
|
||||
try:
|
||||
time_window(mode, count, date.today())
|
||||
except ValueError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
city = str(config.get("city") or "").strip()
|
||||
if len(city) > 32:
|
||||
raise _bad("城市名称过长")
|
||||
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city}
|
||||
|
||||
|
||||
def _public_task(task: ExportTask) -> dict:
|
||||
return {
|
||||
"id": task.id,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""即席查询的分类、表和按相对时间取数。"""
|
||||
|
||||
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 NqiClient, NqiError
|
||||
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 categories(client: NqiClient) -> list[dict]:
|
||||
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 tables(client: NqiClient, code: int) -> list[dict]:
|
||||
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
|
||||
if not isinstance(payload, list):
|
||||
raise NqiError("没有取到这个分类下的表")
|
||||
result = []
|
||||
for row in payload:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
tablename = str(row.get("tablename") or "").strip()
|
||||
name = str(row.get("tablename_cn") or tablename).strip()
|
||||
if tablename:
|
||||
result.append({"tablename": tablename, "name": name})
|
||||
return result
|
||||
|
||||
|
||||
async def export_table(
|
||||
client: NqiClient,
|
||||
tablename: str,
|
||||
start: datetime,
|
||||
end: datetime,
|
||||
city: str,
|
||||
) -> tuple[str, bytes, int]:
|
||||
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
|
||||
@@ -3,16 +3,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.collect.io import parse_upload, write_table
|
||||
from app.collect.remote import fetch_ftp, fetch_nqi
|
||||
from app.config import inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.config import data_dir, inline_worker_allowed, postgres_conninfo, result_dir
|
||||
from app.db import session_scope
|
||||
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
||||
from app.nqi.adhoc import export_table, time_window
|
||||
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
@@ -165,6 +167,13 @@ def execute_collection(source_id: int) -> None:
|
||||
elif kind == "nqi":
|
||||
if not cookies:
|
||||
raise ValueError("账号池里没有可用凭证")
|
||||
if config.get("tables"):
|
||||
_save_nqi_tables(cookies, config, source_id)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
source.last_error = ""
|
||||
return
|
||||
name, content = _fetch_nqi_sync(cookies, config)
|
||||
else:
|
||||
raise ValueError("未知的采集来源")
|
||||
@@ -183,6 +192,40 @@ def execute_collection(source_id: int) -> None:
|
||||
source.last_error = str(exc) or "采集失败"
|
||||
|
||||
|
||||
def _save_nqi_tables(cookies: list, config: dict, source_id: int) -> None:
|
||||
import asyncio
|
||||
|
||||
tables = list(config.get("tables") or [])
|
||||
mode = str(config.get("timeMode") or "")
|
||||
count = int(config.get("timeCount") or 1)
|
||||
city = str(config.get("city") or "")
|
||||
start, end = time_window(mode, count, date.today())
|
||||
|
||||
async def run() -> list[tuple[str, bytes]]:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
try:
|
||||
await client.current_user()
|
||||
except NqiAuthError as exc:
|
||||
raise ValueError("账号池凭证已失效") from exc
|
||||
saved: list[tuple[str, bytes]] = []
|
||||
for table in tables:
|
||||
title, content, _rows = await export_table(client, str(table.get("tablename") or ""), start, end, city)
|
||||
saved.append((str(table.get("name") or title), content))
|
||||
return saved
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
files = asyncio.run(run())
|
||||
folder = data_dir() / "collect" / str(source_id)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
stamp = start.strftime("%Y%m%d")
|
||||
for title, content in files:
|
||||
safe = re.sub(r'[\\/:*?"<>|\s]+', "_", title).strip("._")[:80] or "table"
|
||||
(folder / f"{safe}-{stamp}.csv").write_bytes(content)
|
||||
|
||||
|
||||
def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
import asyncio
|
||||
|
||||
|
||||
Reference in New Issue
Block a user