某網盤上傳文件腳本,使用方法 pcs -f file_name -p target_path html
這裏只展現了代碼,若有疑問,歡迎到個人博客互相交流 http://www.factj.com/archives/508.html python
#!/usr/bin/env python # encoding: utf-8 import os import json import click import requests as r import ConfigParser sess = r.Session() C = {} def load_config(sec="default"): """ 從配置文件讀取帳號信息, 須要 appid, bduss @sec : 讀取的 ini 文件的 section, 預留的多帳號功能 ini 文件格式舉例 [default] appid=266719 ; 應用id bduss=xxxxx ;cookie,此cookie 過時時間很是久,貌似有八九年 """ sc = ConfigParser.SafeConfigParser() cname = ".pcscredentials" f_ = None if os.path.isfile(cname): f_ = cname elif os.path.isfile(os.path.join(os.getenv("HOME"), cname)): f_ = os.path.join(os.getenv("HOME"), cname) elif os.path.isfile(os.path.join("/etc/", cname)): f_ = os.path.join("/etc/", cname) sc.read(f_) C.update(dict(sc.items(sec))) def get_cookie(): """ 爲請求準備的 cookie """ return dict(BDUSS=C['bduss']) def upload_file(name): url = "https://pcs.baidu.com/rest/2.0/pcs/file?method=upload&app_id=%s&type=tmpfile" % C['appid'] with open(name) as uploaded: res = sess.post(url, cookies=get_cookie(), files=[(name, uploaded), ]) d = res.json() return d def create_file(path, data, name=None): url = "https://pcs.baidu.com/rest/2.0/pcs/file?method=createsuperfile&app_id=%s" % C['appid'] if name: path = os.path.join(path, name) str_p = json.dumps(dict(block_list=[data['md5'], ])) res = sess.post(url, params=dict(path=path), data=dict(param=str_p), cookies=get_cookie()) print json.dumps(res.json(), indent=4, ensure_ascii=False) @click.command() @click.option("-f", help=u"文件路徑") @click.option("-p", help=u"保存路徑") @click.option("-c", "--config", default="default", help=u"配置文件名字") def cli(f, p, config): load_config(config) d = upload_file(f) file_name = f.split(os.seq)[-1] if p.endswith("/"): p += file_name create_file(p, d) if __name__ == "__main__": cli()