有没有自动将文件传到百度云的Python脚本,试了一下网页上传比客户端要快

有没有自动将文件 传到百度云的 Python 脚本,试了一下网页上传比客户端要快,客户端还有 500 限制


有没有自动将文件传到百度云的Python脚本,试了一下网页上传比客户端要快
2 回复

有,用百度云的PCS API就行。我写了个脚本,核心是用requests库传文件。你先得去百度开发者中心申请API Key和Secret Key,拿到access_token。

这是主要的上传函数:

import requests
import os
import json

def upload_to_baidupcs(access_token, local_path, remote_dir='/apps/your_app_name/'):
    """
    上传文件到百度云PCS
    
    参数:
        access_token: 百度API的访问令牌
        local_path: 本地文件路径
        remote_dir: 百度云远程目录
    """
    
    # 1. 预上传,获取上传URL
    precreate_url = 'https://pcs.baidu.com/rest/2.0/pcs/file'
    
    file_name = os.path.basename(local_path)
    remote_path = remote_dir + file_name
    
    params = {
        'method': 'precreate',
        'access_token': access_token,
        'path': remote_path,
        'size': os.path.getsize(local_path),
        'isdir': 0,
        'autoinit': 1,
        'rtype': 1
    }
    
    response = requests.post(precreate_url, params=params)
    precreate_data = response.json()
    
    if precreate_data.get('errno') != 0:
        print(f"预上传失败: {precreate_data}")
        return False
    
    # 2. 分片上传(这里简化为单文件上传)
    upload_url = 'https://c.pcs.baidu.com/rest/2.0/pcs/file'
    
    with open(local_path, 'rb') as f:
        files = {'file': (file_name, f)}
        params = {
            'method': 'upload',
            'access_token': access_token,
            'path': remote_path,
            'type': 'tmpfile',
            'uploadid': precreate_data['uploadid'],
            'partseq': 0
        }
        
        response = requests.post(upload_url, params=params, files=files)
        upload_data = response.json()
    
    if upload_data.get('errno') != 0:
        print(f"上传失败: {upload_data}")
        return False
    
    # 3. 创建文件
    create_url = 'https://pcs.baidu.com/rest/2.0/pcs/file'
    params = {
        'method': 'create',
        'access_token': access_token,
        'path': remote_path,
        'size': os.path.getsize(local_path),
        'isdir': 0,
        'uploadid': precreate_data['uploadid'],
        'block_list': json.dumps([precreate_data['block_list'][0]])
    }
    
    response = requests.post(create_url, params=params)
    create_data = response.json()
    
    if create_data.get('errno') == 0:
        print(f"文件上传成功: {remote_path}")
        return True
    else:
        print(f"创建文件失败: {create_data}")
        return False

# 使用示例
if __name__ == "__main__":
    # 替换为你的access_token
    ACCESS_TOKEN = "your_access_token_here"
    
    # 上传文件
    upload_to_baidupcs(
        access_token=ACCESS_TOKEN,
        local_path="/path/to/your/file.txt",
        remote_dir="/apps/your_app_name/"
    )

要跑这个脚本,先装requests:pip install requests。用的时候把ACCESS_TOKEN换成你的,local_path改成要传的文件路径。remote_dir是百度云里的目录,得先在百度开发者平台创建应用。

这脚本走的是百度PCS API,确实比网页上传快,因为跳过了浏览器那层。大文件的话可以加分片上传的逻辑,不过上面这个基础版够用了。

总结:用API直接传比网页快。


有 BYPY 啊,https://github.com/houtianze/bypy

不知有没有自动上传,没有的话自己写个调用就可以了

回到顶部