fix: 下载接口校验保存路径和设置参数,并支持删除任务
This commit is contained in:
@@ -8,15 +8,18 @@ import logging
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
||||
from app.features.download.ids import parse_upload
|
||||
from app.features.download.jobs import run_download
|
||||
from app.features.download.jobs import ensure_output_dir, run_download
|
||||
from app.features.download.journal import explain_os_error
|
||||
from app.platform.client import NqiError
|
||||
from app.platform.constants import CITIES
|
||||
from app.shared.paths import DOWNLOAD_ROOT
|
||||
from app.shared.state import state
|
||||
|
||||
logger = logging.getLogger("nqi.download")
|
||||
@@ -77,6 +80,7 @@ async def meta() -> dict:
|
||||
"LTE": [column.label for column in cell_columns("LTE")],
|
||||
},
|
||||
},
|
||||
"defaultOutputDir": str(DOWNLOAD_ROOT),
|
||||
}
|
||||
|
||||
|
||||
@@ -87,13 +91,18 @@ async def download_settings() -> dict:
|
||||
|
||||
|
||||
@router.put("/settings")
|
||||
async def update_download_settings(body: dict) -> dict:
|
||||
async def update_download_settings(body: Any = Body(default=None)) -> dict:
|
||||
state.require_client()
|
||||
if not isinstance(body, dict):
|
||||
raise _bad("参数格式不正确")
|
||||
try:
|
||||
value = int(body.get("maxConcurrentJobs"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _bad("同时任务数不正确") from exc
|
||||
limit = state.jobs.set_limit(value)
|
||||
try:
|
||||
limit = state.jobs.set_limit(value)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
fill_slots()
|
||||
return {"maxConcurrentJobs": limit}
|
||||
|
||||
@@ -150,7 +159,10 @@ async def create_job(
|
||||
target: Path | None = None
|
||||
if output_dir.strip():
|
||||
folder = Path(output_dir.strip())
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
ensure_output_dir(folder)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
target = folder / f"栅格_{label}_{size_name}_{city['name']}_{month}.csv"
|
||||
whole_city = file is None or not file.filename
|
||||
grid_ids: list[str] = []
|
||||
@@ -164,32 +176,39 @@ async def create_job(
|
||||
raise _bad("区域表是空的")
|
||||
if len(raw) > 20 * 1024 * 1024:
|
||||
raise _bad("区域表不能超过 20MB")
|
||||
job = state.jobs.create(
|
||||
network=network,
|
||||
city_code=city["code"],
|
||||
city_name=city["name"],
|
||||
month=month,
|
||||
groups=selected,
|
||||
concurrency=workers,
|
||||
grid_ids=[],
|
||||
csv_path=target,
|
||||
grid_size=grid_size,
|
||||
whole_city=whole_city,
|
||||
)
|
||||
try:
|
||||
job = state.jobs.create(
|
||||
network=network,
|
||||
city_code=city["code"],
|
||||
city_name=city["name"],
|
||||
month=month,
|
||||
groups=selected,
|
||||
concurrency=workers,
|
||||
grid_ids=[],
|
||||
csv_path=target,
|
||||
grid_size=grid_size,
|
||||
whole_city=whole_city,
|
||||
)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc)) from exc
|
||||
if not whole_city:
|
||||
source = job.directory / "source.csv"
|
||||
source.write_bytes(raw)
|
||||
try:
|
||||
grid_ids, duplicates = parse_upload(source)
|
||||
source.write_bytes(raw)
|
||||
grid_ids, duplicates = await asyncio.to_thread(parse_upload, source, grid_size)
|
||||
except ValueError as exc:
|
||||
_discard_created_job(job)
|
||||
raise _bad(str(exc)) from exc
|
||||
except OSError as exc:
|
||||
_discard_created_job(job)
|
||||
raise _bad(explain_os_error(exc) or f"读取区域表失败:{exc}") from exc
|
||||
except Exception as exc:
|
||||
shutil.rmtree(job.directory, ignore_errors=True)
|
||||
state.jobs.jobs.pop(job.id, None)
|
||||
raise _bad(f"读取区域表失败:{exc}") from exc
|
||||
_discard_created_job(job)
|
||||
raise _bad(explain_os_error(exc) or f"读取区域表失败:{exc}") from exc
|
||||
if not grid_ids:
|
||||
shutil.rmtree(job.directory, ignore_errors=True)
|
||||
state.jobs.jobs.pop(job.id, None)
|
||||
_discard_created_job(job)
|
||||
raise _bad("区域表里没有栅格 ID")
|
||||
job.grid_ids = grid_ids
|
||||
job.store_ids(grid_ids)
|
||||
job.duplicate_count = duplicates
|
||||
if duplicates:
|
||||
job.message = f"已去掉 {duplicates} 个重复栅格"
|
||||
@@ -204,6 +223,30 @@ async def create_job(
|
||||
return job.snapshot()
|
||||
|
||||
|
||||
@router.delete("/jobs/{job_id}")
|
||||
async def delete_job(job_id: str, files: bool = False) -> dict:
|
||||
state.require_client()
|
||||
try:
|
||||
state.jobs.delete(job_id, files=files)
|
||||
except NqiError as exc:
|
||||
status = 404 if str(exc) == "任务不存在" else 400
|
||||
raise _bad(str(exc), status) from exc
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def _discard_created_job(job) -> None:
|
||||
state.jobs.jobs.pop(job.id, None)
|
||||
output = job.csv_path.parent
|
||||
data = job.directory
|
||||
shutil.rmtree(data, ignore_errors=True)
|
||||
try:
|
||||
same = output.resolve() == data.resolve()
|
||||
except OSError:
|
||||
same = False
|
||||
if not same and output.exists():
|
||||
shutil.rmtree(output, ignore_errors=True)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/cancel")
|
||||
async def cancel_job(job_id: str) -> dict:
|
||||
state.require_client()
|
||||
@@ -274,15 +317,3 @@ async def job_events(job_id: str) -> StreamingResponse:
|
||||
job.subscribers.remove(queue)
|
||||
|
||||
return StreamingResponse(stream(), media_type="text/event-stream")
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/file")
|
||||
async def job_file(job_id: str) -> FileResponse:
|
||||
state.require_client()
|
||||
try:
|
||||
job = state.jobs.get(job_id)
|
||||
except NqiError as exc:
|
||||
raise _bad(str(exc), 404) from exc
|
||||
if not job.csv_path.exists():
|
||||
raise _bad("文件还没有生成", 404)
|
||||
return FileResponse(job.csv_path, filename=job.csv_path.name)
|
||||
|
||||
+144
-29
@@ -1,15 +1,19 @@
|
||||
import csv
|
||||
import json
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.features.download import jobs as job_module
|
||||
from app.features.download.ids import parse_table
|
||||
from app.features.download.jobs import JobManager, ensure_output_dir
|
||||
from app.features.download.journal import CsvJournal, explain_os_error
|
||||
from app.main import app
|
||||
from app.platform.client import NqiError
|
||||
from app.shared.state import state
|
||||
|
||||
|
||||
def test_progress_recovers_by_streaming_and_truncates_only_a_bad_tail(tmp_path: Path, monkeypatch):
|
||||
@@ -140,34 +144,6 @@ def test_file_errors_use_chinese(tmp_path: Path, monkeypatch):
|
||||
journal.close()
|
||||
|
||||
|
||||
def test_area_table_rules():
|
||||
try:
|
||||
parse_table([["序号", "栅格编码"], ["1", "541927061"]])
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
else:
|
||||
raise AssertionError("多列且没有编号列时应拒绝")
|
||||
assert parse_table([["541927061"], ["544536471"]]) == (["541927061", "544536471"], 0)
|
||||
try:
|
||||
parse_table([["20米栅格ID"], ["12"]], "GRID50")
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "表头是20米栅格,与所选的50米不一致"
|
||||
else:
|
||||
raise AssertionError("米数不一致时应拒绝")
|
||||
assert parse_table([["栅格ID", "备注"], ["12", "a"]], "GRID50") == (["12"], 0)
|
||||
|
||||
|
||||
def _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
def spy(fd):
|
||||
calls.append(fd)
|
||||
return original(fd)
|
||||
|
||||
monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
|
||||
return calls
|
||||
|
||||
def test_ids_file_replaces_grid_ids_and_release_reloads(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", tmp_path / "jobs")
|
||||
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", tmp_path / "downloads")
|
||||
@@ -374,6 +350,114 @@ def test_delete_rejects_active_jobs_and_optional_files(tmp_path: Path, monkeypat
|
||||
assert active.directory.exists()
|
||||
|
||||
|
||||
def test_area_table_rules():
|
||||
try:
|
||||
parse_table([["序号", "栅格编码"], ["1", "541927061"]])
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
else:
|
||||
raise AssertionError("多列且没有编号列时应拒绝")
|
||||
assert parse_table([["541927061"], ["544536471"]]) == (["541927061", "544536471"], 0)
|
||||
try:
|
||||
parse_table([["20米栅格ID"], ["12"]], "GRID50")
|
||||
except ValueError as exc:
|
||||
assert str(exc) == "表头是20米栅格,与所选的50米不一致"
|
||||
else:
|
||||
raise AssertionError("米数不一致时应拒绝")
|
||||
assert parse_table([["栅格ID", "备注"], ["12", "a"]], "GRID50") == (["12"], 0)
|
||||
|
||||
|
||||
def test_download_api_paths_settings_and_delete(tmp_path: Path, monkeypatch):
|
||||
jobs = tmp_path / "jobs"
|
||||
downloads = tmp_path / "downloads"
|
||||
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
|
||||
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", downloads)
|
||||
monkeypatch.setattr(job_module, "SETTINGS_PATH", tmp_path / "settings.json")
|
||||
monkeypatch.setattr("app.features.download.router.DOWNLOAD_ROOT", downloads)
|
||||
manager = JobManager()
|
||||
manager.max_concurrent = 0
|
||||
monkeypatch.setattr(state, "jobs", manager)
|
||||
monkeypatch.setattr(state, "client", _SilentClient())
|
||||
monkeypatch.setattr(state, "user", {"loginId": "a"})
|
||||
monkeypatch.setattr(state, "expired", False)
|
||||
with TestClient(app) as client:
|
||||
meta = client.get("/api/download/meta")
|
||||
assert meta.status_code == 200
|
||||
assert meta.json()["defaultOutputDir"] == str(downloads)
|
||||
|
||||
rejected = client.put("/api/download/settings", json=["nope"])
|
||||
assert rejected.status_code == 400
|
||||
empty = client.put(
|
||||
"/api/download/settings",
|
||||
content=b"null",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
assert empty.status_code == 400
|
||||
updated = client.put("/api/download/settings", json={"maxConcurrentJobs": 3})
|
||||
assert updated.status_code == 200
|
||||
assert updated.json()["maxConcurrentJobs"] == 3
|
||||
state.jobs.max_concurrent = 0
|
||||
|
||||
relative = _post_job(client, output_dir="relative\\save")
|
||||
assert relative.status_code == 400
|
||||
assert "绝对路径" in relative.json()["detail"]
|
||||
|
||||
blocked = tmp_path / "not-a-folder"
|
||||
blocked.write_text("x", encoding="utf-8")
|
||||
denied = _post_job(client, output_dir=str(blocked))
|
||||
assert denied.status_code == 400
|
||||
assert denied.json()["detail"]
|
||||
|
||||
created = _post_job(client, output_dir="")
|
||||
assert created.status_code == 200
|
||||
body = created.json()
|
||||
assert body["csvPath"].startswith(str(downloads / body["id"]))
|
||||
assert (downloads / body["id"]).is_dir()
|
||||
|
||||
chosen = tmp_path / "chosen"
|
||||
area = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
filename="area.csv",
|
||||
content="20米栅格ID\n541927061\n544536471\n541927061\n".encode("utf-8-sig"),
|
||||
)
|
||||
assert area.status_code == 200
|
||||
saved = area.json()
|
||||
assert Path(saved["csvPath"]).parent == chosen / saved["id"]
|
||||
ids = (jobs / saved["id"] / "ids.txt").read_text(encoding="utf-8").splitlines()
|
||||
assert ids == ["541927061", "544536471"]
|
||||
record = json.loads((jobs / saved["id"] / "job.json").read_text(encoding="utf-8"))
|
||||
assert record["gridCount"] == 2
|
||||
assert "gridIds" not in record
|
||||
|
||||
mismatch = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
grid_size="GRID50",
|
||||
filename="bad.csv",
|
||||
content="20米栅格ID\n12\n".encode("utf-8"),
|
||||
)
|
||||
assert mismatch.status_code == 400
|
||||
assert mismatch.json()["detail"] == "表头是20米栅格,与所选的50米不一致"
|
||||
|
||||
missing = _post_job(
|
||||
client,
|
||||
output_dir=str(chosen),
|
||||
filename="cols.csv",
|
||||
content="序号,栅格编码\n1,12\n".encode("utf-8"),
|
||||
)
|
||||
assert missing.status_code == 400
|
||||
assert missing.json()["detail"] == "请把编号列的表头写成 20米栅格ID 或 50米栅格ID"
|
||||
assert {path.name for path in jobs.iterdir()} == {body["id"], saved["id"]}
|
||||
assert {path.name for path in chosen.iterdir() if path.is_dir()} == {saved["id"]}
|
||||
|
||||
removed = client.delete(f"/api/download/jobs/{saved['id']}?files=true")
|
||||
assert removed.status_code == 200
|
||||
assert removed.json()["ok"] is True
|
||||
assert not (jobs / saved["id"]).exists()
|
||||
assert not (chosen / saved["id"]).exists()
|
||||
assert client.delete(f"/api/download/jobs/{saved['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_output_dir_permission_message(tmp_path: Path, monkeypatch):
|
||||
real_open = Path.open
|
||||
@@ -428,6 +512,22 @@ def test_progress_stats_uses_mtime_cache(tmp_path: Path, monkeypatch):
|
||||
assert job_module._progress_stats(tmp_path) == (2, 3)
|
||||
|
||||
|
||||
def _post_job(client: TestClient, *, output_dir: str, filename: str | None = None, content: bytes | None = None, grid_size: str = "GRID20"):
|
||||
data = {
|
||||
"network": "NR",
|
||||
"city_code": "JM",
|
||||
"month": "2026-09",
|
||||
"groups": "[]",
|
||||
"concurrency": "1",
|
||||
"output_dir": output_dir,
|
||||
"grid_size": grid_size,
|
||||
}
|
||||
files = None
|
||||
if filename is not None:
|
||||
files = {"file": (filename, content or b"", "text/csv")}
|
||||
return client.post("/api/download/jobs", data=data, files=files)
|
||||
|
||||
|
||||
def _write_record(directory: Path, **overrides) -> None:
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
@@ -459,3 +559,18 @@ def _write_record(directory: Path, **overrides) -> None:
|
||||
(directory / "job.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
class _SilentClient:
|
||||
async def aclose(self):
|
||||
return None
|
||||
|
||||
|
||||
def _patch_fsync(monkeypatch):
|
||||
calls = []
|
||||
original = os.fsync
|
||||
|
||||
def spy(fd):
|
||||
calls.append(fd)
|
||||
return original(fd)
|
||||
|
||||
monkeypatch.setattr("app.features.download.journal.os.fsync", spy)
|
||||
return calls
|
||||
|
||||
Reference in New Issue
Block a user