commit
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
"""数据来源抽象。
|
||||
|
||||
本期两种来源:
|
||||
* ``directory`` —— 扫描本地目录(后续替换为 FTP 拉取后的落地目录)。
|
||||
子文件夹里的文件按"网管批量报表"处理,顶层文件按"网页导入"处理。
|
||||
* ``upload`` —— 网页上传,文件落在 ``UPLOAD_DIR`` 下。
|
||||
|
||||
后续接 FTP 时只需新增一个 ``FtpSource``(实现 ``files()`` 即可),
|
||||
入库与导出逻辑完全复用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from . import config
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceFile:
|
||||
path: Path
|
||||
origin: str # web | ftp
|
||||
group: str # 子目录名(批量报表),顶层文件为空串
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.path.name
|
||||
|
||||
|
||||
class Source:
|
||||
kind = "base"
|
||||
|
||||
def __init__(self, ref: str) -> None:
|
||||
self.ref = ref
|
||||
|
||||
def files(self) -> list[SourceFile]: # pragma: no cover - 接口
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class DirectorySource(Source):
|
||||
"""本地目录来源。
|
||||
|
||||
* 顶层 ``*.xlsx`` → origin=web(网页导入)
|
||||
* 子目录内 ``*.xlsx`` → origin=ftp(后续由 FTP 获取)
|
||||
"""
|
||||
|
||||
kind = "directory"
|
||||
|
||||
def files(self) -> list[SourceFile]:
|
||||
root = Path(self.ref).expanduser().resolve()
|
||||
if not root.exists():
|
||||
raise FileNotFoundError(f"数据目录不存在:{root}")
|
||||
out: list[SourceFile] = []
|
||||
for p in sorted(root.iterdir()):
|
||||
if p.is_file() and p.suffix.lower() in (".xlsx", ".xlsm") and not p.name.startswith("~$"):
|
||||
out.append(SourceFile(p, "web", ""))
|
||||
for sub in sorted(x for x in root.iterdir() if x.is_dir()):
|
||||
for p in sorted(sub.rglob("*.xlsx")):
|
||||
if p.name.startswith("~$"):
|
||||
continue
|
||||
out.append(SourceFile(p, "ftp", sub.name))
|
||||
return out
|
||||
|
||||
|
||||
class UploadSource(Source):
|
||||
"""网页上传来源:文件已在 UPLOAD_DIR 中。"""
|
||||
|
||||
kind = "upload"
|
||||
|
||||
def files(self) -> list[SourceFile]:
|
||||
root = Path(self.ref).expanduser().resolve()
|
||||
if not root.exists():
|
||||
raise FileNotFoundError(f"上传目录不存在:{root}")
|
||||
out: list[SourceFile] = []
|
||||
for p in sorted(root.rglob("*.xlsx")):
|
||||
if p.name.startswith("~$"):
|
||||
continue
|
||||
rel = p.relative_to(root)
|
||||
out.append(SourceFile(p, "web", rel.parts[0] if len(rel.parts) > 1 else ""))
|
||||
return out
|
||||
|
||||
|
||||
def resolve(kind: str, ref: str | None = None) -> Source:
|
||||
kind = (kind or "directory").lower()
|
||||
if kind == "directory":
|
||||
return DirectorySource(ref or str(config.DATA_DIR))
|
||||
if kind == "upload":
|
||||
raw = ref or str(config.UPLOAD_DIR)
|
||||
p = Path(raw)
|
||||
if not p.is_absolute(): # 只给了批次名
|
||||
p = Path(config.UPLOAD_DIR) / raw
|
||||
return UploadSource(str(p))
|
||||
raise ValueError(f"不支持的数据来源:{kind}")
|
||||
Reference in New Issue
Block a user