前言
最近有oss文件需求,然后刚好朋友部署了个cloudreve,也能满足轻使用,故此研究了下脚本上传和下载。
具体实现
1、登录拿到cookie
1 2 3 4 5 6 7 8 9
| def login(): url = "https://xxx.cn/api/v3/user/session" payload = { "userName": "xxx", "password": "xxx" } response = requests.post(url, json=payload) cookie = response.cookies['cloudreve-session'] return cookie
|
2、上传文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| def upload_file(cookie, path_dir, file_name="muyu.mp3"): file_size = os.path.getsize(path_dir) upload_policy_url = "https://xxx/api/v3/file/upload" header = { 'cookie': 'cloudreve-session=' + cookie } data = '{"path": "/mp3", "size": %d, "name": "%s","policy_id": "GKH8", "last_modified": 1720575724015, "mime_type": "audio/mpeg"}' % (file_size, file_name)
res = requests.put(upload_policy_url, headers=header, data=data).json() if res.get("code") != 40054: upload_url = f"https://xxx/api/v3/file/upload/{res.get('data').get('sessionID')}/0" with open(path_dir, 'rb') as f: headers = { "Origin": "https://xxx", "Content-Type": "application/octet-stream", "Priority": "u=1, i", "Content-Length": str(file_size), 'cookie': 'cloudreve-session=' + cookie, "Referer":"https://xxx/home?path=%2Fmp3", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36" } try: response = requests.post(upload_url, headers=headers, data=f) if response.json()["code"] == 0: query_list_url = "https://xxx/api/v3/directory%2Fmp3" req = requests.get(query_list_url, headers=header) list_data = req.json()["data"]["objects"][-1]["id"] return query_download_url(cookie, list_data) except: return "" return ""
|
3、获取下载链接
1 2 3 4 5 6 7 8
| def query_download_url(cookie, file_id): url = "https://xxx/api/v3/file/download/" + file_id headers = { 'cookie': 'cloudreve-session=' + cookie } resource = requests.put(url, headers=headers) return "https://xxx" + resource.json().get("data")
|