优化图片上传功能,增加重试机制和超时设置,支持批量上传并发控制

This commit is contained in:
glowzz 2025-03-24 16:17:47 +08:00
parent a5dbe72fe9
commit 16192e00a2

View File

@ -127,23 +127,28 @@ def download_images():
else:
messagebox.showwarning("警告", "没有图片被下载")
def upload_image_to_lsky_pro(image_path):
"""上传图片到Lsky Pro图床"""
with open(image_path, 'rb') as img_file:
files = {'file': img_file}
headers = {
'Authorization': f'Bearer {token}',
'Accept': 'application/json'
}
response = requests.post(f'{lsky_pro_url}{upload_endpoint}', files=files, headers=headers)
if response.status_code == 200:
try:
data = response.json()
if data['status']:
return data['data']['links']['url']
except:
pass
return None
def upload_image_to_lsky_pro(image_path, retries=3, timeout=30):
"""上传图片到Lsky Pro图床增加重试机制和超时设置"""
for attempt in range(retries):
try:
with open(image_path, 'rb') as img_file:
files = {'file': img_file}
headers = {
'Authorization': f'Bearer {token}',
'Accept': 'application/json'
}
response = requests.post(f'{lsky_pro_url}{upload_endpoint}', files=files, headers=headers, timeout=timeout)
if response.status_code == 200:
try:
data = response.json()
if data['status']:
return data['data']['links']['url']
except:
pass
except requests.exceptions.RequestException as e:
print(f"上传失败,重试 {attempt + 1}/{retries}: {str(e)}")
time.sleep(3) # 重试前等待3秒
return None
@ -309,24 +314,18 @@ def download_and_upload_images():
except Exception as e:
messagebox.showerror("错误", f"处理过程中出错: {str(e)}")
def upload_images_batch_files(file_paths, max_concurrent_uploads=5):
"""批量上传图片,限制并发上传数量"""
from concurrent.futures import ThreadPoolExecutor, as_completed
def upload_images_batch_files(file_paths):
# """ 你的图片上传逻辑(需自行实现) """
for file_path in file_paths:
# 这里添加处理每个文件的逻辑
if not file_path or not os.path.isfile(file_path):
messagebox.showwarning("警告", "请选择有效的Markdown文件。")
return
print(f"Processing: {file_path}")
process_image_file(file_path)
# 示例读取markdown文件内容
# with open(file_path, 'r') as f:
# content = f.read()
# 添加你的图片上传逻辑...
with ThreadPoolExecutor(max_workers=max_concurrent_uploads) as executor:
futures = {executor.submit(process_image_file, file_path): file_path for file_path in file_paths}
for future in as_completed(futures):
file_path = futures[future]
try:
future.result()
except Exception as e:
print(f"处理文件 {file_path} 时出错: {str(e)}")
def select_files():
root = tk.Tk()