Skip to content

Latest commit

 

History

History
111 lines (89 loc) · 2.99 KB

File metadata and controls

111 lines (89 loc) · 2.99 KB

优化说明

主要改进

1. 代码质量

  • ✅ 添加类型注解 (Type Hints)
  • ✅ 使用 PEP 8 命名规范 (snake_case)
  • ✅ 移除注释掉的代码和调试语句
  • ✅ 统一字符串格式化 (f-strings)
  • ✅ 使用 isinstance() 替代 type() == type()

2. Bug 修复

  • ✅ 修复 add_torrent 方法中未定义变量 torrent_file_position 的错误
  • ✅ 修复 get_global_optionchange_global_option 不应该需要 gid 参数的问题
  • ✅ 移除无用的 nofification 方法 (拼写错误且未完成)

3. 代码简化

  • ✅ 消除重复的异常处理代码
  • ✅ 使用属性装饰器 (@property) 简化 URL 和 token 的获取
  • ✅ 提取公共方法 _normalize_keys_normalize_uris 减少重复
  • ✅ 简化 setServer 参数处理逻辑

4. 设计改进

  • ✅ 支持在初始化时直接传入配置参数
  • ✅ 移除不必要的 rpc 变量,直接硬编码为常量
  • ✅ 使用常量定义默认值 (DEFAULT_HOST, DEFAULT_PORT 等)
  • ✅ 改进文档字符串格式 (Google 风格)

5. 结构优化

  • ✅ 将代码重命名为 aria2_client.py 更语义化
  • ✅ 添加 __init__.py 使其成为标准的 Python 包
  • ✅ 添加 example.py 演示正确用法
  • ✅ 使用可选类型 Optional[str] 明确参数可否为空

对比示例

原始代码

def setServer(self, server_add='', server_port='6800', token=''):
    #server信息更改
    rpc = "rpc"
    
    #更改服务器地址
    if server_add == '':
        pass
    else:
        if server_add[-1] == "/":
            server_add = server_add[:-1]
        self.server_add = server_add
    
    #更改端口
    if server_port == '':
        pass
    else:
        self.server_port = str(server_port)
    
    if token == '':
        pass
    else:
        self.token = str(token)
    
    self.server_url = self.server_add + ":" + self.server_port + "/" + rpc
    self.server = xmlrpc_client.ServerProxy(self.server_url)

优化后代码

def set_server(
    self,
    host: Optional[str] = None,
    port: Optional[int] = None,
    token: Optional[str] = None,
) -> None:
    """Update server connection settings."""
    if host is not None:
        self._host = host.rstrip("/")
    if port is not None:
        self._port = port
    if token is not None:
        self._token = token
    self._server = self._create_server_proxy()

使用方法

from aria2_client import Aria2Client

# 初始化
client = Aria2Client(host="http://127.0.0.1", port=6800, token="your_token")

# 添加下载
gid = client.add_uri("https://example.com/file.zip")

# 查看状态
status = client.tell_status(gid, ["gid", "status"])

# 暂停下载
client.pause(gid)

向后兼容

原始的 Aria2Client 类名仍然可用,但方法名已更新为 PEP 8 规范:

  • setServer()set_server()
  • addUri()add_uri()
  • addTorrent()add_torrent()
  • checkConnection()check_connection()
  • ... 等

建议迁移到新的命名规范。