From a8854edd9283c324dfaea9b2db53ddd8298120c5 Mon Sep 17 00:00:00 2001 From: han0 Date: Wed, 22 Mar 2023 09:13:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(core.file):=20=E6=96=B0=E5=A2=9E=20save=5F?= =?UTF-8?q?file=20=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nc_http/core/file/__init__.py | 0 nc_http/core/file/func.py | 29 +++++++++++++++++++++++++++++ nc_http/tools/helpers/file.py | 15 --------------- 3 files changed, 29 insertions(+), 15 deletions(-) create mode 100644 nc_http/core/file/__init__.py create mode 100644 nc_http/core/file/func.py diff --git a/nc_http/core/file/__init__.py b/nc_http/core/file/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nc_http/core/file/func.py b/nc_http/core/file/func.py new file mode 100644 index 0000000..b571dcc --- /dev/null +++ b/nc_http/core/file/func.py @@ -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) diff --git a/nc_http/tools/helpers/file.py b/nc_http/tools/helpers/file.py index 202215e..e69de29 100644 --- a/nc_http/tools/helpers/file.py +++ b/nc_http/tools/helpers/file.py @@ -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