项目基础模块代码

This commit is contained in:
2025-02-19 11:47:33 +08:00
parent 3cb2a4c507
commit 31302bcd17
30 changed files with 588 additions and 74 deletions

43
app/util/os_utils.py Normal file
View File

@ -0,0 +1,43 @@
import os
from fastapi import UploadFile
from PIL import Image
def create_folder(*path):
"""根据路径创建文件夹"""
folder_path = os.path.join(*path)
try:
os.makedirs(path, exist_ok=True)
except Exception as e:
print(f"创建文件夹时错误: {e}")
def save_images(*path, file: UploadFile):
"""
保存上传的图片
:param path: 路径
:param file: 文件
:return:
"""
save_path = os.path.join(*path, file.filename)
with open(save_path, "wb") as f:
for line in file.file:
f.write(line)
return save_path
def create_thumbnail(input_image_path, out_image_path, size=(116, 70)):
"""
给图片生成缩略图
:param input_image_path:
:param out_image_path:
:param size: 缩略的尺寸
:return:
"""
with Image.open(input_image_path) as image:
# 使用thumbnail方法生成缩略图参数size指定缩略图的最大尺寸
# 注意thumbnail方法会保持图片的宽高比不变
image.thumbnail(size)
# 保存生成的缩略图
image.save(out_image_path, 'JPEG')

12
app/util/random_utils.py Normal file
View File

@ -0,0 +1,12 @@
import random
import string
def random_str(length=10):
"""随机生成自定义长度的小写字母"""
letters = string.ascii_lowercase
# 使用 random.choices 从 letters 中随机选择 length 个字母,返回一个列表
random_letters = random.choices(letters, k=length)
# 将列表中的字母连接成一个字符串
return ''.join(random_letters)