feat(core.file): 新增 save_file 函数

This commit is contained in:
han0
2023-03-22 09:13:22 +08:00
parent 6f004e73fd
commit a8854edd92
3 changed files with 29 additions and 15 deletions

View File

29
nc_http/core/file/func.py Normal file
View File

@@ -0,0 +1,29 @@
import os
import time
import requests
from werkzeug.datastructures import FileStorage
def download_file(url: str, path: str) -> str:
r = requests.get(url)
with open(path, 'wb') as f:
f.write(r.content)
return path
def save_file(f: FileStorage, path: str, namespace: str=None, filename: str=None) -> str:
if namespace:
save_path = os.path.join(path, namespace.replace('.', os.path.sep))
else:
save_path = path
if not os.path.exists(save_path):
os.makedirs(save_path)
filename = filename or '{}{}'.format(str(int(time.time() * 1000)), os.path.splitext(f.name)[-1])
file_path = os.path.join(save_path, filename)
with open(file_path, 'wb+') as tmp_f:
tmp_f.write(f.read())
return os.path.join(save_path, filename)

View File

@@ -1,15 +0,0 @@
import os
import time
def save_file(f, clip=None, root=None):
clip = clip or ''
clip_path = os.path.join(root, clip, str(int(time.time())))
if not os.path.exists(clip_path):
os.makedirs(clip_path)
file_path = os.path.join(clip_path, f.filename)
with open(file_path, 'wb+') as tmp_f:
tmp_f.write(f.read())
return file_path