From 56757b81017a45030b0495032b4c15a4541226e1 Mon Sep 17 00:00:00 2001 From: lizhikang <2445667550@qq.com> Date: Wed, 7 Feb 2024 21:48:35 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20WriteXlsx=20=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=20static=20=E5=88=9B=E5=BB=BA=E9=BB=98=E8=AE=A4=20exc?= =?UTF-8?q?el=20=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kinit-api/utils/excel/write_xlsx.py | 15 +++++--- kinit-api/utils/file/file_base.py | 56 ++++++++++++++++++++++------- 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/kinit-api/utils/excel/write_xlsx.py b/kinit-api/utils/excel/write_xlsx.py index 7e7b05f..a2c36bc 100644 --- a/kinit-api/utils/excel/write_xlsx.py +++ b/kinit-api/utils/excel/write_xlsx.py @@ -16,7 +16,7 @@ from typing import List from application.settings import STATIC_ROOT, STATIC_URL from utils.file.file_base import FileBase -from utils.tools import generate_string +from pathlib import Path class WriteXlsx: @@ -38,13 +38,19 @@ def create_excel(self, file_path: str = None, sheet_name: str = "sheet1", save_s :param save_static: 保存方式 static 静态资源或者临时文件 :return: """ - if not file_path or (file_path and not os.path.abspath(file_path)): + if not file_path: if save_static: - self.file_path = FileBase.generate_static_file_path("write_xlsx", file_path) + self.file_path = FileBase.generate_static_file_path(path="write_xlsx", suffix="xlsx") else: - self.file_path = FileBase.generate_temp_file_path(f"{generate_string(8)}.xlsx") + self.file_path = FileBase.generate_temp_file_path(suffix="xlsx") + elif not os.path.isabs(file_path): + if save_static: + self.file_path = FileBase.generate_static_file_path(path="write_xlsx", filename=file_path) + else: + self.file_path = FileBase.generate_temp_file_path(filename=file_path) else: self.file_path = file_path + Path(self.file_path).parent.mkdir(parents=True, exist_ok=True) self.sheet_name = sheet_name self.wb = xlsxwriter.Workbook(self.file_path) self.sheet = self.wb.add_worksheet(sheet_name) @@ -121,4 +127,3 @@ def get_file_url(self) -> str: print("write_xlsx 生成文件:", self.file_path) raise ValueError("生成文件为临时文件,无法访问!") - diff --git a/kinit-api/utils/file/file_base.py b/kinit-api/utils/file/file_base.py index a0c96ef..e909014 100644 --- a/kinit-api/utils/file/file_base.py +++ b/kinit-api/utils/file/file_base.py @@ -11,7 +11,7 @@ from pathlib import Path from aiopathlib import AsyncPath from fastapi import UploadFile -from application.settings import TEMP_DIR +from application.settings import TEMP_DIR, STATIC_ROOT from core.exception import CustomException from utils import status from utils.tools import generate_string @@ -25,30 +25,61 @@ class FileBase: ALL_ACCEPT = [*IMAGE_ACCEPT, *VIDEO_ACCEPT, *AUDIO_ACCEPT] @classmethod - def generate_static_file_path(cls, path: str, filename: str) -> str: + def get_random_filename(cls, suffix: str) -> str: """ - 生成文件路径 + 生成随机文件名称,生成规则:当前时间戳 + 8位随机字符串拼接 + :param suffix: 文件后缀 + :return: + """ + if not suffix.startswith("."): + suffix = "." + suffix + return f"{str(int(datetime.datetime.now().timestamp())) + str(generate_string(8))}{suffix}" + + @classmethod + def get_today_timestamp(cls) -> str: + """ + 获取当天时间戳 + :return: + """ + return str(int((datetime.datetime.now().replace(hour=0, minute=0, second=0)).timestamp())) + + @classmethod + def generate_static_file_path(cls, path: str, filename: str = None, suffix: str = None) -> str: + """ + 生成 static 静态文件路径,生成规则:自定义目录/当天日期时间戳/随机文件名称 + 1. filename 参数或者 suffix 参数必须填写一个 + 2. filename 参数和 suffix 参数都存在则优先取 suffix 参数为后缀 :param path: static 指定目录类别 :param filename: 文件名称 + :param suffix: 文件后缀 :return: """ + if not filename and not suffix: + raise ValueError("filename 参数或者 suffix 参数必须填写一个") + elif not suffix and filename: + suffix = os.path.splitext(filename)[-1] path = path.replace("\\", "/") if path[0] == "/": path = path[1:] if path[-1] == "/": path = path[:-1] - today = str(int((datetime.datetime.now().replace(hour=0, minute=0, second=0)).timestamp())) - _filename = str(int(datetime.datetime.now().timestamp())) + str(generate_string(8)) - return f"{path}/{today}/{_filename}{os.path.splitext(filename)[-1]}" + return f"{STATIC_ROOT}/{path}/{cls.get_today_timestamp()}/{cls.get_random_filename(suffix)}" @classmethod - def generate_temp_file_path(cls, filename: str) -> str: + def generate_temp_file_path(cls, filename: str = None, suffix: str = None) -> str: """ - 生成临时文件路径 + 生成临时文件路径,生成规则: + 1. filename 参数或者 suffix 参数必须填写一个 + 2. filename 参数和 suffix 参数都存在则优先取 suffix 参数为后缀 :param filename: 文件名称 + :param suffix: 文件后缀 :return: """ - return f"{cls.generate_temp_dir_path()}/{filename}" + if not filename and not suffix: + raise ValueError("filename 参数或者 suffix 参数必须填写一个") + elif not suffix and filename: + suffix = os.path.splitext(filename)[-1] + return f"{cls.generate_temp_dir_path()}/{cls.get_random_filename(suffix)}" @classmethod def generate_temp_dir_path(cls) -> str: @@ -58,10 +89,9 @@ def generate_temp_dir_path(cls) -> str: """ date = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d") file_dir = Path(TEMP_DIR) / date - path = file_dir / (generate_string(4) + str(int(datetime.datetime.now().timestamp()))) - if not path.exists(): - path.mkdir(parents=True, exist_ok=True) - return str(path).replace("\\", "/") + if not file_dir.exists(): + file_dir.mkdir(parents=True, exist_ok=True) + return str(file_dir).replace("\\", "/") @classmethod async def async_generate_temp_file_path(cls, filename: str) -> str: