feat: 采集按分组选表和固定时刻运行,号池可检查凭证,管理页不再退出
This commit is contained in:
+73
-25
@@ -15,11 +15,12 @@ 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.collect.schedule import next_run_at, parse_schedule
|
||||
from app.nqi.adhoc import TIME_MODES, catalog_tree, 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
|
||||
from app.tasks.runner import check_concurrency, check_period, check_refresh, enqueue_export
|
||||
from app.tasks.runner import check_concurrency, check_refresh, enqueue_export
|
||||
|
||||
router = APIRouter(prefix="/api")
|
||||
# 在响应发出前提交,客户端紧接着发出的请求才能读到刚写入的内容。
|
||||
@@ -443,21 +444,69 @@ def admin_dashboard(actor: Actor = Depends(current_actor), session: Session = db
|
||||
def list_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
|
||||
return {"accounts": [_public_account(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/admin/pool/check")
|
||||
def check_pool(actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
rows = session.scalars(select(NqiAccount).order_by(NqiAccount.id.desc())).all()
|
||||
for row in rows:
|
||||
_check_account(row)
|
||||
return {"accounts": [_public_account(row) for row in rows]}
|
||||
|
||||
|
||||
@router.post("/admin/pool/{account_id}/check")
|
||||
def check_pool_account(account_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
account = session.get(NqiAccount, account_id)
|
||||
if account is None:
|
||||
raise _bad("账号不存在", 404)
|
||||
_check_account(account)
|
||||
return {"account": _public_account(account)}
|
||||
|
||||
|
||||
def _public_account(row: NqiAccount) -> dict:
|
||||
return {
|
||||
"accounts": [
|
||||
{
|
||||
"id": row.id,
|
||||
"loginId": row.login_id,
|
||||
"userName": row.user_name,
|
||||
"cityName": row.city_name,
|
||||
"sessionOpen": row.session_open,
|
||||
"credentialValid": row.credential_valid,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
"id": row.id,
|
||||
"loginId": row.login_id,
|
||||
"userName": row.user_name,
|
||||
"cityName": row.city_name,
|
||||
"credentialValid": row.credential_valid,
|
||||
"savedAt": row.saved_at.isoformat() if row.saved_at else "",
|
||||
"createdAt": row.created_at.isoformat() if row.created_at else "",
|
||||
}
|
||||
|
||||
|
||||
def _check_account(account: NqiAccount) -> None:
|
||||
cookies = list(account.cookies or [])
|
||||
if not cookies:
|
||||
account.credential_valid = False
|
||||
account.saved_at = utcnow()
|
||||
return
|
||||
|
||||
async def run() -> tuple[bool, list]:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
await client.current_user()
|
||||
await client.renew_ticket()
|
||||
return True, client.export_cookies()
|
||||
except NqiAuthError:
|
||||
return False, cookies
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
try:
|
||||
valid, refreshed = asyncio.run(run())
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
account.credential_valid = valid
|
||||
account.saved_at = utcnow()
|
||||
if valid:
|
||||
account.cookies = refreshed
|
||||
|
||||
|
||||
@router.delete("/admin/pool/{account_id}")
|
||||
def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
@@ -469,7 +518,7 @@ def delete_pool(account_id: int, actor: Actor = Depends(current_actor), session:
|
||||
|
||||
|
||||
@router.get("/admin/nqi/catalog")
|
||||
def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
def nqi_catalog(code: int | None = None, tree: bool = False, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
cookies = _pool_cookies(session)
|
||||
|
||||
@@ -479,6 +528,8 @@ def nqi_catalog(code: int | None = None, actor: Actor = Depends(current_actor),
|
||||
client.import_cookies(cookies)
|
||||
await client.current_user()
|
||||
try:
|
||||
if tree:
|
||||
return {"groups": await catalog_tree(client)}
|
||||
if code is None:
|
||||
return {"categories": await categories(client)}
|
||||
return {"tables": await tables(client, code)}
|
||||
@@ -513,7 +564,7 @@ def list_sources(actor: Actor = Depends(current_actor), session: Session = db_se
|
||||
@router.post("/admin/sources")
|
||||
def create_source(body: dict, actor: Actor = Depends(current_actor), session: Session = db_session) -> dict:
|
||||
require_admin(actor)
|
||||
source = CollectionSource(name="采集", kind="ftp", period_days=1, config={}, enabled=True, next_run_at=utcnow())
|
||||
source = CollectionSource(name="采集", kind="nqi", period_days=1, config={}, enabled=True)
|
||||
_apply_source(source, body)
|
||||
session.add(source)
|
||||
session.flush()
|
||||
@@ -545,14 +596,9 @@ def _apply_source(source: CollectionSource, body: dict) -> None:
|
||||
source.name = str(body.get("name") or "").strip() or source.name
|
||||
if "kind" in body:
|
||||
kind = str(body.get("kind") or "")
|
||||
if kind not in {"ftp", "nqi"}:
|
||||
raise _bad("采集来源不正确")
|
||||
if kind != "nqi":
|
||||
raise _bad("只采集 NQI")
|
||||
source.kind = kind
|
||||
if "periodDays" in body:
|
||||
try:
|
||||
source.period_days = check_period(int(body.get("periodDays")))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
if "enabled" in body:
|
||||
source.enabled = bool(body.get("enabled"))
|
||||
if "config" in body and isinstance(body.get("config"), dict):
|
||||
@@ -560,8 +606,9 @@ 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:
|
||||
if source.kind == "nqi":
|
||||
incoming = _nqi_tables(incoming)
|
||||
source.next_run_at = next_run_at(incoming["schedule"], utcnow())
|
||||
source.config = incoming
|
||||
|
||||
|
||||
@@ -591,12 +638,13 @@ def _nqi_tables(config: dict) -> dict:
|
||||
raise _bad("时间数量不正确") from exc
|
||||
try:
|
||||
time_window(mode, count, date.today())
|
||||
schedule = parse_schedule(config.get("schedule"))
|
||||
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}
|
||||
return {**config, "tables": cleaned, "timeMode": mode, "timeCount": count, "city": city, "schedule": schedule}
|
||||
|
||||
|
||||
def _public_task(task: ExportTask) -> dict:
|
||||
@@ -633,7 +681,7 @@ def _pool_dashboard(rows: list[NqiAccount]) -> dict:
|
||||
added_today = 0
|
||||
added_week = 0
|
||||
for row in rows:
|
||||
saved = _as_utc(row.saved_at)
|
||||
saved = _as_utc(row.created_at)
|
||||
if saved is not None:
|
||||
day = saved.date()
|
||||
key = day.isoformat()
|
||||
|
||||
@@ -1,46 +1,12 @@
|
||||
"""从 FTP/SFTP 或已登录的大数据平台取回表格。"""
|
||||
"""从已登录的大数据平台取回表格。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from ftplib import FTP
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import paramiko
|
||||
|
||||
from app.nqi.client import NqiClient
|
||||
|
||||
|
||||
def fetch_ftp(config: dict) -> tuple[str, bytes]:
|
||||
protocol = str(config.get("protocol") or "sftp")
|
||||
host = str(config.get("host") or "")
|
||||
path = str(config.get("path") or "")
|
||||
username = str(config.get("username") or "")
|
||||
password = str(config.get("password") or "")
|
||||
port = int(config.get("port") or (21 if protocol == "ftp" else 22))
|
||||
if not host or not path:
|
||||
raise ValueError("请填写主机和路径")
|
||||
if protocol == "ftp":
|
||||
ftp = FTP()
|
||||
ftp.connect(host, port, timeout=30)
|
||||
ftp.login(username, password)
|
||||
buffer = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buffer.write)
|
||||
ftp.quit()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
transport = paramiko.Transport((host, port))
|
||||
transport.connect(username=username, password=password)
|
||||
sftp = paramiko.SFTPClient.from_transport(transport)
|
||||
if sftp is None:
|
||||
transport.close()
|
||||
raise ValueError("无法连接 SFTP")
|
||||
buffer = io.BytesIO()
|
||||
sftp.getfo(path, buffer)
|
||||
sftp.close()
|
||||
transport.close()
|
||||
return path.rsplit("/", 1)[-1], buffer.getvalue()
|
||||
|
||||
|
||||
async def fetch_nqi(client: NqiClient, config: dict) -> tuple[str, bytes]:
|
||||
address = str(config.get("url") or "").strip()
|
||||
if not address:
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""采集按每周某天或每月某日的时刻运行。时间按北京时间计算。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ZONE = ZoneInfo("Asia/Shanghai")
|
||||
TIME_RE = re.compile(r"^(\d{2}):(\d{2})$")
|
||||
|
||||
|
||||
def parse_schedule(raw: object) -> dict:
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("请设置采集周期")
|
||||
mode = raw.get("mode")
|
||||
if mode not in {"weekly", "monthly"}:
|
||||
raise ValueError("请设置采集周期")
|
||||
hour, minute = _clock(raw.get("time"))
|
||||
if mode == "weekly":
|
||||
weekday = _int(raw.get("weekday"), "请选择星期")
|
||||
if weekday < 1 or weekday > 7:
|
||||
raise ValueError("请选择星期")
|
||||
return {"mode": mode, "weekday": weekday, "time": f"{hour:02d}:{minute:02d}"}
|
||||
month_day = _int(raw.get("monthDay"), "请选择日期")
|
||||
if month_day < 1 or month_day > 31:
|
||||
raise ValueError("请选择日期")
|
||||
return {"mode": mode, "monthDay": month_day, "time": f"{hour:02d}:{minute:02d}"}
|
||||
|
||||
|
||||
def next_run_at(schedule: dict, now: datetime) -> datetime:
|
||||
local = now.astimezone(ZONE)
|
||||
hour, minute = _clock(schedule["time"])
|
||||
if schedule["mode"] == "weekly":
|
||||
target = local.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
target += timedelta(days=(schedule["weekday"] - 1 - local.weekday()) % 7)
|
||||
if target <= local:
|
||||
target += timedelta(days=7)
|
||||
else:
|
||||
target = _monthly(local.year, local.month, schedule["monthDay"], hour, minute)
|
||||
if target <= local:
|
||||
year, month = (local.year + 1, 1) if local.month == 12 else (local.year, local.month + 1)
|
||||
target = _monthly(year, month, schedule["monthDay"], hour, minute)
|
||||
return target.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _monthly(year: int, month: int, day: int, hour: int, minute: int) -> datetime:
|
||||
last = calendar.monthrange(year, month)[1]
|
||||
return datetime(year, month, min(day, last), hour, minute, tzinfo=ZONE)
|
||||
|
||||
|
||||
def _clock(value: object) -> tuple[int, int]:
|
||||
match = TIME_RE.fullmatch(str(value or ""))
|
||||
if not match:
|
||||
raise ValueError("请填写采集时间")
|
||||
hour, minute = int(match.group(1)), int(match.group(2))
|
||||
if hour > 23 or minute > 59:
|
||||
raise ValueError("请填写采集时间")
|
||||
return hour, minute
|
||||
|
||||
|
||||
def _int(value: object, message: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(message) from exc
|
||||
@@ -51,6 +51,7 @@ class NqiAccount(Base):
|
||||
role: Mapped[str] = mapped_column(String(16), default="user")
|
||||
session_open: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
credential_valid: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
saved_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
|
||||
|
||||
@@ -85,19 +85,46 @@ async def categories(client: NqiClient) -> list[dict]:
|
||||
return result
|
||||
|
||||
|
||||
async def tables(client: NqiClient, code: int) -> list[dict]:
|
||||
async def catalog_tree(client: NqiClient) -> list[dict]:
|
||||
await ensure_session(client)
|
||||
payload = await _post_json(client, f"{PAGE}/searchSecondMenu", {"code": code})
|
||||
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):
|
||||
raise NqiError("没有取到这个分类下的表")
|
||||
return []
|
||||
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()
|
||||
title = str(row.get("tablename_cn") or tablename).strip()
|
||||
if tablename:
|
||||
result.append({"tablename": tablename, "name": name})
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ 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.collect.remote import fetch_nqi
|
||||
from app.collect.schedule import next_run_at
|
||||
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
|
||||
@@ -162,9 +163,7 @@ def execute_collection(source_id: int) -> None:
|
||||
else:
|
||||
cookies = []
|
||||
try:
|
||||
if kind == "ftp":
|
||||
name, content = fetch_ftp(config)
|
||||
elif kind == "nqi":
|
||||
if kind == "nqi":
|
||||
if not cookies:
|
||||
raise ValueError("账号池里没有可用凭证")
|
||||
if config.get("tables"):
|
||||
@@ -278,9 +277,23 @@ def scan_sources() -> None:
|
||||
with session_scope() as session:
|
||||
sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all()
|
||||
for source in sources:
|
||||
if source.next_run_at is not None and source.next_run_at > now:
|
||||
if source.kind != "nqi":
|
||||
source.enabled = False
|
||||
source.last_error = "不再从 FTP 采集"
|
||||
continue
|
||||
source.next_run_at = now + timedelta(days=source.period_days)
|
||||
schedule = (source.config or {}).get("schedule")
|
||||
if not isinstance(schedule, dict) or not schedule.get("mode"):
|
||||
if source.next_run_at is not None and source.next_run_at > now:
|
||||
continue
|
||||
source.next_run_at = now + timedelta(days=source.period_days)
|
||||
due_ids.append(source.id)
|
||||
continue
|
||||
if source.next_run_at is None:
|
||||
source.next_run_at = next_run_at(schedule, now)
|
||||
continue
|
||||
if source.next_run_at > now:
|
||||
continue
|
||||
source.next_run_at = next_run_at(schedule, now)
|
||||
due_ids.append(source.id)
|
||||
for source_id in due_ids:
|
||||
enqueue_collection(source_id)
|
||||
|
||||
Reference in New Issue
Block a user