import requests import json import os from requests.exceptions import RequestException CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'config.json') def load_config(): if os.path.exists(CONFIG_PATH): with open(CONFIG_PATH, 'r') as f: return json.load(f) 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}") 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" 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: try: return response.json() except json.JSONDecodeError: raise Exception("服务器响应格式错误") else: 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): 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}") if response.status_code == 200: try: return response.json() except json.JSONDecodeError: return None else: return None