Files

70 lines
2.2 KiB
Python
Raw Permalink Normal View History

2026-05-24 22:36:01 +08:00
import requests
import json
import os
from requests.exceptions import RequestException
2026-05-24 22:36:01 +08:00
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.json')
def load_config():
if os.path.exists(CONFIG_PATH):
2026-05-24 22:42:55 +08:00
try:
with open(CONFIG_PATH, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
return {"server_url": "http://localhost:5000", "default_expiry": "24h"}
2026-05-24 22:36:01 +08:00
return {"server_url": "http://localhost:5000", "default_expiry": "24h"}
def save_config(config):
try:
with open(CONFIG_PATH, 'w') as f:
json.dump(config, f, indent=4)
except IOError as e:
raise Exception(f"保存配置失败: {e}")
2026-05-24 22:36:01 +08:00
def upload_file(filepath, expiry='24h', server_url=None):
2026-05-24 22:36:01 +08:00
if server_url is None:
config = load_config()
server_url = config.get('server_url', 'http://localhost:5000')
url = f"{server_url}/api/upload"
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}")
2026-05-24 22:36:01 +08:00
if response.status_code == 200:
try:
return response.json()
except json.JSONDecodeError:
raise Exception("服务器响应格式错误")
2026-05-24 22:36:01 +08:00
else:
try:
error_msg = response.json().get('error', '未知错误')
except json.JSONDecodeError:
error_msg = '未知错误'
2026-05-24 22:36:01 +08:00
raise Exception(f"上传失败: {error_msg}")
def get_file_info(file_id, 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/file/{file_id}"
try:
response = requests.get(url, timeout=30)
except RequestException as e:
raise Exception(f"网络请求失败: {e}")
2026-05-24 22:36:01 +08:00
if response.status_code == 200:
try:
return response.json()
except json.JSONDecodeError:
return None
2026-05-24 22:36:01 +08:00
else:
return None