kinit/kinit-api/utils/file/file_base.py
ktianc 4320d2db82 feat:接口异常描述
fix:接口注释
fix:前端认证过期提示
2023-05-05 15:00:22 +08:00

67 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version : 1.0
# @Create Time : 2022/12/12 14:31
# @File : file_base.py
# @IDE : PyCharm
# @desc : 简要说明
import datetime
import os
import uuid
from fastapi import UploadFile
from core.exception import CustomException
from utils import status
class FileBase:
IMAGE_ACCEPT = ["image/png", "image/jpeg", "image/gif", "image/x-icon"]
VIDEO_ACCEPT = ["audio/mp4", "video/mp4", "video/mpeg"]
ALL_ACCEPT = [*IMAGE_ACCEPT, *VIDEO_ACCEPT]
@classmethod
def generate_path(cls, path: str, filename):
"""
生成文件路径
"""
if path[0] == "/":
path = path[1:]
if path[-1] == "/":
path = path[:-1]
full_date = datetime.datetime.now().date()
_filename = str(int(datetime.datetime.now().timestamp())) + str(uuid.uuid4())[:8]
return f"{path}/{full_date}/{_filename}{os.path.splitext(filename)[-1]}"
@classmethod
async def validate_file(cls, file: UploadFile, max_size: int = None, mime_types: list = None) -> bool:
"""
验证文件是否符合格式
:params max_size: 文件最大值,单位 MB
"""
if max_size:
size = len(await file.read()) / 1024 / 1024
if size > max_size:
raise CustomException(f"上传文件过大,不能超过{max_size}MB", status.HTTP_ERROR)
await file.seek(0)
if mime_types:
if file.content_type not in mime_types:
raise CustomException(f"上传文件格式错误,只支持 {'/'.join(mime_types)} 格式!", status.HTTP_ERROR)
return True
@classmethod
def get_file_type(cls, content_type: str) -> str | None:
"""
获取文件类型
0: 图片
1视频
"""
if content_type in cls.IMAGE_ACCEPT:
return "0"
elif content_type in cls.VIDEO_ACCEPT:
return "1"
else:
return None