feat: 采集结果按数据表写入数据库并替换同一批
This commit is contained in:
+30
-15
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
@@ -12,7 +11,8 @@ from sqlalchemy import select
|
||||
from app.collect.io import parse_upload, write_table
|
||||
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.collect.store import replace_batch
|
||||
from app.config import 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
|
||||
@@ -154,6 +154,7 @@ def execute_collection(source_id: int) -> None:
|
||||
return
|
||||
kind = source.kind
|
||||
config = dict(source.config or {})
|
||||
source_name = source.name
|
||||
account = None
|
||||
if kind == "nqi":
|
||||
account = session.scalar(
|
||||
@@ -167,7 +168,7 @@ def execute_collection(source_id: int) -> None:
|
||||
if not cookies:
|
||||
raise ValueError("账号池里没有可用凭证")
|
||||
if config.get("tables"):
|
||||
_save_nqi_tables(cookies, config, source_id)
|
||||
_save_nqi_tables(cookies, config, source_id, source_name)
|
||||
with session_scope() as session:
|
||||
source = session.get(CollectionSource, source_id)
|
||||
if source is not None:
|
||||
@@ -191,16 +192,19 @@ 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:
|
||||
def _save_nqi_tables(cookies: list, config: dict, source_id: int, source_name: str) -> None:
|
||||
import asyncio
|
||||
|
||||
from app.db import engine
|
||||
|
||||
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 "")
|
||||
schedule = config.get("schedule") if isinstance(config.get("schedule"), dict) else {}
|
||||
start, end = time_window(mode, count, date.today())
|
||||
|
||||
async def run() -> list[tuple[str, bytes]]:
|
||||
async def run() -> list[tuple[str, list[dict], list[dict]]]:
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(cookies)
|
||||
@@ -208,21 +212,32 @@ def _save_nqi_tables(cookies: list, config: dict, source_id: int) -> None:
|
||||
await client.current_user()
|
||||
except NqiAuthError as exc:
|
||||
raise ValueError("账号池凭证已失效") from exc
|
||||
saved: list[tuple[str, bytes]] = []
|
||||
saved: list[tuple[str, list[dict], list[dict]]] = []
|
||||
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))
|
||||
tablename = str(table.get("tablename") or "")
|
||||
_title, columns, rows = await export_table(client, tablename, start, end, city)
|
||||
saved.append((tablename, columns, rows))
|
||||
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)
|
||||
batches = asyncio.run(run())
|
||||
with engine().begin() as connection:
|
||||
for tablename, columns, rows in batches:
|
||||
replace_batch(
|
||||
connection,
|
||||
tablename,
|
||||
columns,
|
||||
rows,
|
||||
task_id=source_id,
|
||||
task_name=source_name,
|
||||
time_mode=mode,
|
||||
time_count=count,
|
||||
window_start=start,
|
||||
window_end=end,
|
||||
city=city,
|
||||
schedule=schedule,
|
||||
)
|
||||
|
||||
|
||||
def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
||||
|
||||
Reference in New Issue
Block a user