Skip to content

Commit

Permalink
!9 修复 WriteXlsx 使用 static 创建默认 excel 问题
Browse files Browse the repository at this point in the history
Merge pull request !9 from ktianc/master
  • Loading branch information
ktianc authored and gitee-org committed Feb 7, 2024
2 parents 19a19b4 + 56757b8 commit 09abd68
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 18 deletions.
15 changes: 10 additions & 5 deletions kinit-api/utils/excel/write_xlsx.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -121,4 +127,3 @@ def get_file_url(self) -> str:
print("write_xlsx 生成文件:", self.file_path)
raise ValueError("生成文件为临时文件,无法访问!")


56 changes: 43 additions & 13 deletions kinit-api/utils/file/file_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand Down

0 comments on commit 09abd68

Please sign in to comment.