Commit d8cb820a by 江名洋

refactor(file-upload): 重构文件上传存储逻辑,新增草稿临时目录

修复临时目录路径问题,新增temp_uploads/drafts目录存放未正式保存的临时文件。重构核心文件处理函数,优化文件名与存储路径规则,更新所有上传接口适配新存储结构。
1 parent 60947560
No preview for this file type
...@@ -37,11 +37,22 @@ router = APIRouter() ...@@ -37,11 +37,22 @@ router = APIRouter()
UPLOAD_BASE = "temp_uploads" UPLOAD_BASE = "temp_uploads"
os.makedirs(UPLOAD_BASE, exist_ok=True) os.makedirs(UPLOAD_BASE, exist_ok=True)
# 临时目录,用于存放未正式保存的文件
DRAFT_BASE = os.path.join(UPLOAD_BASE, "drafts")
os.makedirs(DRAFT_BASE, exist_ok=True)
def _date_path(filename: str, category: str = "") -> str: def _date_path(filename: str, category: str = "") -> str:
"""生成按日期分级的文件路径: temp_uploads/YYYYMMDD/filename""" """生成文件路径:
today = datetime.now().strftime("%Y%m%d") - 如果 category="drafts",则存放在 temp_uploads/drafts/filename
target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today) - 否则存放在 temp_uploads/category/YYYYMMDD/filename
"""
if category == "drafts":
target_dir = DRAFT_BASE
else:
today = datetime.now().strftime("%Y%m%d")
target_dir = os.path.join(UPLOAD_BASE, category, today) if category else os.path.join(UPLOAD_BASE, today)
os.makedirs(target_dir, exist_ok=True) os.makedirs(target_dir, exist_ok=True)
return os.path.join(target_dir, filename) return os.path.join(target_dir, filename)
...@@ -67,7 +78,7 @@ async def upload_data( ...@@ -67,7 +78,7 @@ async def upload_data(
# 记录接收到的参数,方便调试 422 错误 # 记录接收到的参数,方便调试 422 错误
logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}") logger.info(f"Upload request received: filename={file.filename}, table_name={table_name}, upload_type={upload_type}, tag={version_tag}")
file_path = _date_path(file.filename) file_path = _date_path(file.filename, category="drafts")
try: try:
# 1. 保存临时文件 # 1. 保存临时文件
with open(file_path, "wb") as buffer: with open(file_path, "wb") as buffer:
...@@ -358,38 +369,27 @@ _analysis_nature_factory_file = None # 缓存自然月主机厂文件路径 ...@@ -358,38 +369,27 @@ _analysis_nature_factory_file = None # 缓存自然月主机厂文件路径
def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str: def _build_dated_filename(original_name: str, prefix: str, start_date: str = None, end_date: str = None) -> str:
"""构建带日期范围的文件名: 使用新的命名规范 """构建带日期范围的文件名:
- 如果提供日期,则按正式命名规范整理
支持的 prefix: - 否则返回带前缀和时间戳的临时名称
- analysis_store: 问界门店数据
- analysis_ecology: 问界主机厂数据(生态月)
- analysis_nature: 问界主机厂数据(自然月)
- harmony_store: 鸿蒙门店数据
- harmony_factory: 鸿蒙主机厂数据
""" """
# 使用统一的命名规范 # 只有在提供日期范围时才应用正式命名规范
if "store" in prefix and "harmony" not in prefix: if start_date and end_date:
return build_store_filename("问界", start_date, end_date) if "store" in prefix and "harmony" not in prefix:
elif "ecology" in prefix: return build_store_filename("问界", start_date, end_date)
return build_factory_filename("问界", "生态月", start_date, end_date) elif "ecology" in prefix:
elif "nature" in prefix: return build_factory_filename("问界", "生态月", start_date, end_date)
return build_factory_filename("问界", "自然月", start_date, end_date) elif "nature" in prefix:
elif "harmony_store" in prefix: return build_factory_filename("问界", "自然月", start_date, end_date)
return build_store_filename("鸿蒙", start_date, end_date) elif "harmony_store" in prefix:
elif "harmony_factory" in prefix: return build_store_filename("鸿蒙", start_date, end_date)
return build_factory_filename("鸿蒙", "", start_date, end_date) elif "harmony_factory" in prefix:
return build_factory_filename("鸿蒙", "", start_date, end_date)
# 回退到旧的命名方式 # 没有日期范围时,使用临时命名方式
stem, ext = os.path.splitext(original_name) stem, ext = os.path.splitext(original_name)
parts = [prefix, stem] ts = datetime.now().strftime("%H%M%S")
if start_date and end_date: return f"{prefix}_{stem}_{ts}{ext}"
s = start_date[5:].replace("-", "") if len(start_date) >= 10 else start_date
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(f"{s}~{e}")
elif end_date:
e = end_date[5:].replace("-", "") if len(end_date) >= 10 else end_date
parts.append(e)
return "_".join(parts) + ext
@router.post("/analysis/upload") @router.post("/analysis/upload")
...@@ -406,8 +406,9 @@ async def analysis_upload( ...@@ -406,8 +406,9 @@ async def analysis_upload(
result = {"status": "success", "messages": []} result = {"status": "success", "messages": []}
if store_file and store_file.filename: if store_file and store_file.filename:
# 门店文件通常不带日期上传,先存入 drafts 目录
fname = _build_dated_filename(store_file.filename, "analysis_store") fname = _build_dated_filename(store_file.filename, "analysis_store")
file_path = _date_path(fname, category="analysis") file_path = _date_path(fname, category="drafts")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f) shutil.copyfileobj(store_file.file, f)
global _analysis_store_file global _analysis_store_file
...@@ -418,7 +419,9 @@ async def analysis_upload( ...@@ -418,7 +419,9 @@ async def analysis_upload(
if not upload_file or not upload_file.filename: if not upload_file or not upload_file.filename:
return None return None
fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date) fname = _build_dated_filename(upload_file.filename, f"analysis_{prefix}", start_date, end_date)
file_path = _date_path(fname, category="analysis") # 如果没有日期范围,则存入 drafts 目录
cat = "analysis" if (start_date and end_date) else "drafts"
file_path = _date_path(fname, category=cat)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(upload_file.file, f) shutil.copyfileobj(upload_file.file, f)
try: try:
...@@ -467,7 +470,19 @@ async def analysis_save_batch( ...@@ -467,7 +470,19 @@ async def analysis_save_batch(
if not file.filename: if not file.filename:
raise HTTPException(status_code=400, detail="请选择文件") raise HTTPException(status_code=400, detail="请选择文件")
file_path = _date_path(f"_save_batch_{file.filename}", category="batch") # 保存为历史时,按命名规范整理文件名
if file_type == "store":
formal_name = build_store_filename(brand, period_start, period_end)
else:
# 主机厂数据
pt = period_type or ("生态月" if file_type == "ecology" else "自然月")
formal_name = build_factory_filename(brand, pt, period_start, period_end)
# 确保文件名唯一并保存到 batch 目录
file_path = _date_path(formal_name, category="batch")
file_path = ensure_unique_filename(os.path.dirname(file_path), os.path.basename(file_path))
file_path = os.path.join(os.path.dirname(file_path), os.path.basename(file_path)) # ensure_unique_filename returns name only or path?
# Let's check ensure_unique_filename definition in file_naming.py
try: try:
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
...@@ -619,7 +634,7 @@ async def analysis_preview_file( ...@@ -619,7 +634,7 @@ async def analysis_preview_file(
file: UploadFile = File(...), file: UploadFile = File(...),
): ):
"""上传分析文件并返回解析后的预览数据""" """上传分析文件并返回解析后的预览数据"""
file_path = _date_path(f"_preview_{file.filename}") file_path = _date_path(f"_preview_{file.filename}", category="drafts")
try: try:
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
...@@ -754,7 +769,7 @@ async def harmony_upload( ...@@ -754,7 +769,7 @@ async def harmony_upload(
if store_file and store_file.filename: if store_file and store_file.filename:
fname = _build_dated_filename(store_file.filename, "harmony_store") fname = _build_dated_filename(store_file.filename, "harmony_store")
file_path = _date_path(fname, category="harmony") file_path = _date_path(fname, category="drafts")
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(store_file.file, f) shutil.copyfileobj(store_file.file, f)
_harmony_store_file = file_path _harmony_store_file = file_path
...@@ -762,7 +777,9 @@ async def harmony_upload( ...@@ -762,7 +777,9 @@ async def harmony_upload(
if factory_file and factory_file.filename: if factory_file and factory_file.filename:
fname = _build_dated_filename(factory_file.filename, "harmony_factory", start_date, end_date) fname = _build_dated_filename(factory_file.filename, "harmony_factory", start_date, end_date)
file_path = _date_path(fname, category="harmony") # 如果没有日期范围,则存入 drafts 目录
cat = "harmony" if (start_date and end_date) else "drafts"
file_path = _date_path(fname, category=cat)
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(factory_file.file, f) shutil.copyfileobj(factory_file.file, f)
_harmony_factory_file = file_path _harmony_factory_file = file_path
...@@ -1031,12 +1048,28 @@ async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)): ...@@ -1031,12 +1048,28 @@ async def strategy_stale_list(stale_hours: int = Query(4, ge=1, le=48)):
DATA_UPLOAD_CATEGORY = "data" DATA_UPLOAD_CATEGORY = "data"
def _save_upload(file: UploadFile, brand: str, data_type: str) -> tuple: def _save_upload(file: UploadFile, brand: str, data_type: str, start_date: str = None, end_date: str = None, period_type: str = "") -> tuple:
"""保存上传文件到按日期分级的目录,返回 (文件路径, 原始文件名)""" """保存上传文件。
ts = datetime.now().strftime("%H%M%S") - 如果提供日期范围,则按正式命名规范整理并存入 data 目录
base, ext = os.path.splitext(file.filename) - 否则存入 drafts 目录
safe_name = f"{data_type}_{brand}_{ts}{ext}" """
file_path = _date_path(safe_name, category=DATA_UPLOAD_CATEGORY) if start_date and end_date:
if data_type == "store":
formal_name = build_store_filename(brand, start_date, end_date)
else:
formal_name = build_factory_filename(brand, period_type, start_date, end_date)
cat = DATA_UPLOAD_CATEGORY
file_name = formal_name
else:
ts = datetime.now().strftime("%H%M%S")
base, ext = os.path.splitext(file.filename)
file_name = f"{data_type}_{brand}_{ts}{ext}"
cat = "drafts"
file_path = _date_path(file_name, category=cat)
# 确保文件名唯一
file_path = ensure_unique_filename(os.path.dirname(file_path), os.path.basename(file_path))
file_path = os.path.join(os.path.dirname(file_path), os.path.basename(file_path))
with open(file_path, "wb") as f: with open(file_path, "wb") as f:
shutil.copyfileobj(file.file, f) shutil.copyfileobj(file.file, f)
...@@ -1058,7 +1091,7 @@ async def upload_store_guarantee( ...@@ -1058,7 +1091,7 @@ async def upload_store_guarantee(
if brand not in ("问界", "鸿蒙"): if brand not in ("问界", "鸿蒙"):
raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙") raise HTTPException(status_code=400, detail="品牌仅支持 问界 或 鸿蒙")
file_path, original_name = _save_upload(file, brand, "store") file_path, original_name = _save_upload(file, brand, "store", start_date=period_start, end_date=period_end)
try: try:
file_size = os.path.getsize(file_path) file_size = os.path.getsize(file_path)
...@@ -1097,7 +1130,7 @@ async def upload_oem_delivery( ...@@ -1097,7 +1130,7 @@ async def upload_oem_delivery(
if period_type not in ("", "ecology", "nature"): if period_type not in ("", "ecology", "nature"):
raise HTTPException(status_code=400, detail="周期类型仅支持 ecology 或 nature") raise HTTPException(status_code=400, detail="周期类型仅支持 ecology 或 nature")
file_path, original_name = _save_upload(file, brand, "oem") file_path, original_name = _save_upload(file, brand, "oem", start_date=period_start, end_date=period_end, period_type=period_type)
try: try:
file_size = os.path.getsize(file_path) file_size = os.path.getsize(file_path)
......
...@@ -22,7 +22,7 @@ def create_excel_file(file_path): ...@@ -22,7 +22,7 @@ def create_excel_file(file_path):
wb.save(file_path) wb.save(file_path)
def main(): def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads' temp_uploads_dir = Path(__file__).parent.parent / 'temp_uploads'
# 确保目录存在 # 确保目录存在
temp_uploads_dir.mkdir(exist_ok=True) temp_uploads_dir.mkdir(exist_ok=True)
......
...@@ -170,7 +170,7 @@ class FilenameNormalizer: ...@@ -170,7 +170,7 @@ class FilenameNormalizer:
print(f"[完成] 重命名了 {count} 个文件") print(f"[完成] 重命名了 {count} 个文件")
def main(): def main():
target_dir = Path(__file__).parent / 'temp_uploads' target_dir = Path(__file__).parent.parent / 'temp_uploads'
normalizer = FilenameNormalizer(target_dir) normalizer = FilenameNormalizer(target_dir)
......
...@@ -187,7 +187,7 @@ def normalize_directory(directory, dry_run=True): ...@@ -187,7 +187,7 @@ def normalize_directory(directory, dry_run=True):
def main(): def main():
temp_uploads_dir = "temp_uploads" temp_uploads_dir = str(Path(__file__).parent.parent / 'temp_uploads')
if len(sys.argv) > 1 and sys.argv[1] == "--run": if len(sys.argv) > 1 and sys.argv[1] == "--run":
# 实际执行 # 实际执行
......
...@@ -69,7 +69,7 @@ def normalize_filename(filename): ...@@ -69,7 +69,7 @@ def normalize_filename(filename):
return name + ext return name + ext
def main(): def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads' temp_uploads_dir = Path(__file__).parent.parent / 'temp_uploads'
if not temp_uploads_dir.exists(): if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}') print(f'目录不存在: {temp_uploads_dir}')
......
...@@ -81,7 +81,7 @@ def build_filename(info): ...@@ -81,7 +81,7 @@ def build_filename(info):
return None return None
def main(): def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads' temp_uploads_dir = Path(__file__).parent.parent / 'temp_uploads'
if not temp_uploads_dir.exists(): if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}') print(f'目录不存在: {temp_uploads_dir}')
......
...@@ -84,7 +84,7 @@ def normalize_filename(filename): ...@@ -84,7 +84,7 @@ def normalize_filename(filename):
return new_name return new_name
def main(): def main():
temp_uploads_dir = Path(__file__).parent / 'temp_uploads' temp_uploads_dir = Path(__file__).parent.parent / 'temp_uploads'
if not temp_uploads_dir.exists(): if not temp_uploads_dir.exists():
print(f'目录不存在: {temp_uploads_dir}') print(f'目录不存在: {temp_uploads_dir}')
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!