fix: improve error handling and add timeouts

This commit is contained in:
OpenCode Bot
2026-05-24 22:39:58 +08:00
parent 213716fa44
commit 38a273eb3d

View File

@@ -1,6 +1,7 @@
import requests
import json
import os
from requests.exceptions import RequestException
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.json')
@@ -11,26 +12,38 @@ def load_config():
return {"server_url": "http://localhost:5000", "default_expiry": "24h"}
def save_config(config):
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=4)
try:
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=4)
except IOError as e:
raise Exception(f"保存配置失败: {e}")
def upload_file(filepath, expiry='24h', server_url=None, progress_callback=None):
def upload_file(filepath, expiry='24h', server_url=None):
if server_url is None:
config = load_config()
server_url = config.get('server_url', 'http://localhost:5000')
url = f"{server_url}/api/upload"
with open(filepath, 'rb') as f:
files = {'file': (os.path.basename(filepath), f)}
data = {'expiry': expiry}
response = requests.post(url, files=files, data=data)
try:
with open(filepath, 'rb') as f:
files = {'file': (os.path.basename(filepath), f)}
data = {'expiry': expiry}
response = requests.post(url, files=files, data=data, timeout=30)
except RequestException as e:
raise Exception(f"网络请求失败: {e}")
if response.status_code == 200:
return response.json()
try:
return response.json()
except json.JSONDecodeError:
raise Exception("服务器响应格式错误")
else:
error_msg = response.json().get('error', '未知错误')
try:
error_msg = response.json().get('error', '未知错误')
except json.JSONDecodeError:
error_msg = '未知错误'
raise Exception(f"上传失败: {error_msg}")
def get_file_info(file_id, server_url=None):
@@ -39,9 +52,16 @@ def get_file_info(file_id, server_url=None):
server_url = config.get('server_url', 'http://localhost:5000')
url = f"{server_url}/api/file/{file_id}"
response = requests.get(url)
try:
response = requests.get(url, timeout=30)
except RequestException as e:
raise Exception(f"网络请求失败: {e}")
if response.status_code == 200:
return response.json()
try:
return response.json()
except json.JSONDecodeError:
return None
else:
return None