bypy API文档:第三方集成开发指南
1. 简介
bypy是百度云/百度网盘的Python客户端(Python client for Baidu Yun/Personal Cloud Storage),提供了丰富的API接口,方便开发者进行第三方集成开发。本文档将详细介绍bypy的API接口,包括初始化、认证、文件操作、目录操作等方面,帮助开发者快速上手并进行集成开发。
2. 环境准备
2.1 安装bypy
可以通过以下命令安装bypy:
pip install bypy
2.2 获取仓库
如果需要获取源码进行开发,可以通过以下命令克隆仓库:
git clone https://gitcode.com/gh_mirrors/by/bypy
3. 核心类与初始化
3.1 ByPy类
ByPy类是bypy的核心类,提供了与百度云/百度网盘交互的各种方法。其构造函数如下:
def __init__(self,
slice_size = const.DefaultSliceSize,
dl_chunk_size = const.DefaultDlChunkSize,
verify = True,
retry = 5, timeout = const.DefaultTimeOutInSeconds,
quit_when_fail = False,
resumedownload = True,
extraupdate = lambda: (),
incregex = '',
ondup = '',
followlink = True,
checkssl = True,
cacerts = None,
rapiduploadonly = False,
mirror = '',
selectmirror = False,
resumedl_revertcount = const.DefaultResumeDlRevertCount,
deletesource = False,
verbose = 0, debug = False,
configdir = const.ConfigDir,
requester = RequestsRequester,
apikey = const.ApiKey,
downloader = "",
downloader_args = "",
processes = const.DefaultProcessCount,
secretkey = const.SecretKey)
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| slice_size | int | const.DefaultSliceSize | 上传文件时的分片大小 |
| dl_chunk_size | int | const.DefaultDlChunkSize | 下载文件时的分片大小 |
| verify | bool | True | 是否验证SSL证书 |
| retry | int | 5 | 请求失败时的重试次数 |
| timeout | int | const.DefaultTimeOutInSeconds | 请求超时时间(秒) |
| quit_when_fail | bool | False | 请求失败时是否退出 |
| resumedownload | bool | True | 是否支持断点续传 |
| extraupdate | function | lambda: () | 额外的更新函数 |
| incregex | str | '' | 包含的正则表达式 |
| ondup | str | '' | 文件重复时的处理方式 |
| followlink | bool | True | 是否跟随符号链接 |
| checkssl | bool | True | 是否检查SSL |
| cacerts | str | None | CA证书路径 |
| rapiduploadonly | bool | False | 是否仅支持极速上传 |
| mirror | str | '' | 镜像地址 |
| selectmirror | bool | False | 是否选择镜像 |
| resumedl_revertcount | int | const.DefaultResumeDlRevertCount | 断点续传时的回退次数 |
| deletesource | bool | False | 操作完成后是否删除源文件 |
| verbose | int | 0 | 详细日志级别 |
| debug | bool | False | 是否开启调试模式 |
| configdir | str | const.ConfigDir | 配置目录 |
| requester | class | RequestsRequester | 请求器类 |
| apikey | str | const.ApiKey | API密钥 |
| downloader | str | "" | 下载器 |
| downloader_args | str | "" | 下载器参数 |
| processes | int | const.DefaultProcessCount | 进程数 |
| secretkey | str | const.SecretKey | 密钥 |
3.2 初始化示例
from bypy import ByPy
# 创建ByPy实例
bp = ByPy(debug=True, verbose=2)
4. 认证相关接口
4.1 刷新令牌
def refreshtoken(self)
功能:刷新访问令牌。
示例:
bp.refreshtoken()
4.2 获取用户信息
def whoami(self)
功能:获取当前登录用户信息。
返回值:包含用户信息的字典。
示例:
user_info = bp.whoami()
print(user_info)
5. 文件操作接口
5.1 上传文件
def upload(self, localpath = '', remotepath = '', ondup = "overwrite")
功能:上传本地文件到百度网盘。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| localpath | str | '' | 本地文件路径 |
| remotepath | str | '' | 远程文件路径 |
| ondup | str | "overwrite" | 文件重复时的处理方式,可选值:"overwrite"(覆盖)、"skip"(跳过)、"rename"(重命名) |
示例:
# 上传本地文件test.txt到远程根目录
bp.upload(localpath='test.txt', remotepath='/test.txt', ondup='overwrite')
5.2 下载文件
def downfile(self, remotefile, localpath = '')
功能:从百度网盘下载文件到本地。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| remotefile | str | - | 远程文件路径 |
| localpath | str | '' | 本地文件路径 |
示例:
# 下载远程文件/test.txt到本地当前目录
bp.downfile(remotefile='/test.txt', localpath='./test.txt')
5.3 获取文件信息
def get_file_info(self, remotefile = '/')
功能:获取远程文件信息。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| remotefile | str | '/' | 远程文件路径 |
返回值:包含文件信息的字典。
示例:
file_info = bp.get_file_info(remotefile='/test.txt')
print(file_info)
5.4 删除文件
def delete(self, remotepath)
功能:删除百度网盘中的文件。
参数说明
| 参数名 | 类型 | 描述 |
|---|---|---|
| remotepath | str | 远程文件路径 |
示例:
bp.delete(remotepath='/test.txt')
6. 目录操作接口
6.1 创建目录
def mkdir(self, remotepath)
功能:在百度网盘创建目录。
参数说明
| 参数名 | 类型 | 描述 |
|---|---|---|
| remotepath | str | 远程目录路径 |
示例:
bp.mkdir(remotepath='/test_dir')
6.2 列出目录
def list(self, remotepath = '', fmt = '$t $f $s $m $d', sort = 'name', order = 'asc')
功能:列出远程目录下的文件和子目录。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| remotepath | str | '' | 远程目录路径 |
| fmt | str | '$t $f $s $m $d' | 输出格式 |
| sort | str | 'name' | 排序字段,可选值:'name'(名称)、'size'(大小)、'mtime'(修改时间) |
| order | str | 'asc' | 排序顺序,可选值:'asc'(升序)、'desc'(降序) |
返回值:包含目录列表信息的字典。
示例:
dir_list = bp.list(remotepath='/test_dir', sort='size', order='desc')
print(dir_list)
6.3 下载目录
def downdir(self, remotepath = None, localpath = None)
功能:从百度网盘下载目录到本地。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| remotepath | str | None | 远程目录路径 |
| localpath | str | None | 本地目录路径 |
示例:
bp.downdir(remotepath='/test_dir', localpath='./test_dir')
6.4 删除目录
def delete(self, remotepath)
功能:删除百度网盘中的目录(包含目录下的所有文件和子目录)。
参数说明
| 参数名 | 类型 | 描述 |
|---|---|---|
| remotepath | str | 远程目录路径 |
示例:
bp.delete(remotepath='/test_dir')
7. 目录同步接口
7.1 同步本地目录到远程
def syncup(self, localdir = '', remotedir = '', deleteremote = False)
功能:将本地目录同步到百度网盘远程目录。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| localdir | str | '' | 本地目录路径 |
| remotedir | str | '' | 远程目录路径 |
| deleteremote | bool | False | 是否删除远程目录中本地不存在的文件 |
示例:
# 将本地目录./local_dir同步到远程目录/test_sync,删除远程多余文件
bp.syncup(localdir='./local_dir', remotedir='/test_sync', deleteremote=True)
7.2 同步远程目录到本地
def syncdown(self, remotedir = '', localdir = '', deletelocal = False)
功能:将百度网盘远程目录同步到本地目录。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| remotedir | str | '' | 远程目录路径 |
| localdir | str | '' | 本地目录路径 |
| deletelocal | bool | False | 是否删除本地目录中远程不存在的文件 |
示例:
# 将远程目录/test_sync同步到本地目录./local_sync,删除本地多余文件
bp.syncdown(remotedir='/test_sync', localdir='./local_sync', deletelocal=True)
8. 其他常用接口
8.1 获取配额信息
def quota(self)
功能:获取百度网盘的配额信息(总空间、已用空间等)。
返回值:包含配额信息的字典。
示例:
quota_info = bp.quota()
print(f"总空间: {quota_info['total']}B, 已用空间: {quota_info['used']}B")
8.2 搜索文件/目录
def search(self, keyword, remotepath = None, recursive = True)
功能:在百度网盘中搜索文件或目录。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| keyword | str | - | 搜索关键词 |
| remotepath | str | None | 搜索的起始远程路径,None表示根目录 |
| recursive | bool | True | 是否递归搜索子目录 |
返回值:包含搜索结果的字典。
示例:
search_result = bp.search(keyword='test', remotepath='/test_dir', recursive=True)
print(search_result)
8.3 移动/重命名文件/目录
def move(self, fromp, to)
功能:移动或重命名百度网盘中的文件或目录。
参数说明
| 参数名 | 类型 | 描述 |
|---|---|---|
| fromp | str | 源路径 |
| to | str | 目标路径 |
示例:
# 重命名文件
bp.move(fromp='/test.txt', to='/test_new.txt')
# 移动目录
bp.move(fromp='/test_dir', to='/new_dir/test_dir')
8.4 复制文件/目录
def copy(self, fromp, to)
功能:复制百度网盘中的文件或目录。
参数说明
| 参数名 | 类型 | 描述 |
|---|---|---|
| fromp | str | 源路径 |
| to | str | 目标路径 |
示例:
# 复制文件
bp.copy(fromp='/test.txt', to='/test_copy.txt')
# 复制目录
bp.copy(fromp='/test_dir', to='/test_dir_copy')
9. 高级接口
9.1 离线下载
def cdl_add(self, source_url, save_path = '/', timeout = 3600)
功能:添加离线下载任务。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| source_url | str | - | 要下载的资源URL |
| save_path | str | '/' | 保存到百度网盘的路径 |
| timeout | int | 3600 | 任务超时时间(秒) |
返回值:包含任务ID等信息的字典。
示例:
task_info = bp.cdl_add(source_url='http://example.com/file.zip', save_path='/downloads/')
print(f"离线下载任务ID: {task_info['task_id']}")
9.2 查询离线下载任务状态
def cdl_query(self, task_ids, op_type = 1)
功能:查询离线下载任务状态。
参数说明
| 参数名 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| task_ids | list | - | 任务ID列表 |
| op_type | int | 1 | 操作类型,1表示查询 |
返回值:包含任务状态信息的字典。
示例:
task_ids = ['task_id_1', 'task_id_2']
task_status = bp.cdl_query(task_ids=task_ids)
print(task_status)
10. 错误处理
在使用bypy API时,可能会遇到各种错误。以下是一些常见的错误处理方式:
10.1 捕获异常
try:
# 执行API调用
bp.upload('test.txt', '/test.txt')
except Exception as e:
# 处理异常
print(f"上传文件失败: {str(e)}")
10.2 错误码说明
bypy API返回的错误信息中通常包含错误码,以下是一些常见的错误码:
| 错误码 | 描述 |
|---|---|
| 1 | 请求失败 |
| 100 | 参数错误 |
| 111 | 访问令牌无效 |
| 112 | 访问令牌过期 |
| 200 | 文件不存在 |
| 201 | 目录不存在 |
| 302 | 空间不足 |
11. 多线程与多进程
bypy支持多线程和多进程操作,以提高文件上传和下载的效率。可以通过processes参数设置进程数。
11.1 多进程上传示例
# 设置进程数为4进行多进程上传
bp = ByPy(processes=4)
bp.upload('large_file.zip', '/large_file.zip')
12. 完整示例:文件备份工具
以下是一个使用bypy API实现的简单文件备份工具,将本地目录备份到百度网盘:
from bypy import ByPy
import os
import time
def backup_to_baiduyun(local_dir, remote_dir, delete_remote=False):
"""
将本地目录备份到百度网盘
:param local_dir: 本地目录路径
:param remote_dir: 百度网盘远程目录路径
:param delete_remote: 是否删除远程目录中本地不存在的文件
"""
try:
# 创建ByPy实例
bp = ByPy(debug=True, verbose=1)
# 检查本地目录是否存在
if not os.path.isdir(local_dir):
print(f"本地目录不存在: {local_dir}")
return
# 确保远程目录存在
try:
bp.mkdir(remote_dir)
except Exception as e:
print(f"创建远程目录失败,可能已存在: {str(e)}")
# 同步本地目录到远程
print(f"开始同步 {local_dir} 到 {remote_dir} ...")
start_time = time.time()
bp.syncup(localdir=local_dir, remotedir=remote_dir, deleteremote=delete_remote)
end_time = time.time()
print(f"同步完成,耗时: {end_time - start_time:.2f}秒")
# 获取配额信息,检查空间使用情况
quota = bp.quota()
used_gb = quota['used'] / (1024 **3)
total_gb = quota['total'] / (1024** 3)
print(f"百度网盘空间使用情况: {used_gb:.2f}GB / {total_gb:.2f}GB")
except Exception as e:
print(f"备份失败: {str(e)}")
if __name__ == "__main__":
# 本地目录
LOCAL_BACKUP_DIR = "./my_files"
# 百度网盘远程目录
REMOTE_BACKUP_DIR = "/backups/my_files"
# 执行备份,不删除远程多余文件
backup_to_baiduyun(LOCAL_BACKUP_DIR, REMOTE_BACKUP_DIR, delete_remote=False)
13. 总结
本文档详细介绍了bypy API的核心接口,包括初始化、认证、文件操作、目录操作、同步、搜索等功能。通过这些接口,开发者可以方便地集成百度网盘的功能到自己的应用中。在使用过程中,建议注意错误处理和异常捕获,以提高应用的稳定性。
如需了解更多详细信息,可以查看bypy的源码或官方文档。
如果你觉得本文档对你有帮助,请点赞、收藏并关注,以便获取更多相关内容!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



