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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
import requests import time
class WeChatCloudStorage: def __init__(self, appid, secret, env): self.appid = appid self.secret = secret self.env = env self.access_token = None self.token_expires = 0
def _refresh_access_token(self): """获取或刷新access_token""" url = "https://api.weixin.qq.com/cgi-bin/token" params = { "grant_type": "client_credential", "appid": self.appid, "secret": self.secret } response = requests.get(url, params=params, verify=False).json() if 'access_token' in response: self.access_token = response['access_token'] self.token_expires = time.time() + response['expires_in'] - 300 else: raise Exception(f"获取access_token失败: {response}")
def _ensure_access_token(self): """确保access_token有效""" if time.time() >= self.token_expires or not self.access_token: self._refresh_access_token()
def upload_file(self, local_path, cloud_path): """ 上传本地文件到微信云存储 :param local_path: 本地文件路径 :param cloud_path: 云端存储路径(如:'images/example.jpg') :return: 文件ID(用于后续下载) """ self._ensure_access_token() upload_meta_url = "https://api.weixin.qq.com/tcb/uploadfile" params = {"access_token": self.access_token} payload = {"env": self.env, "path": cloud_path} response = requests.post(upload_meta_url, params=params, json=payload,verify=False).json() print(payload, params) if response.get('errcode', 0) != 0: raise Exception(f"上传元数据获取失败: {response}") cos_url = response['url'] key = cloud_path.split('/')[-1] print(key) files = { "Signature":(None,response['authorization']), "x-cos-meta-fileid": (None, response['cos_file_id']), "x-cos-security-token": (None,response['token']), "key": (None, cloud_path), 'file':(key, open(local_path, 'rb')), }
upload_resp = requests.post(cos_url, files=files, verify=False) if upload_resp.status_code != 204: raise Exception(f"COS上传失败: {upload_resp.text}", upload_resp) return response['file_id']
def download_file(self, file_id, local_path): """ 从微信云存储下载文件 :param file_id: 文件ID(上传时返回的file_id) :param local_path: 本地存储路径 """ self._ensure_access_token() download_meta_url = "https://api.weixin.qq.com/tcb/batchdownloadfile" params = {"access_token": self.access_token} payload = { "env": self.env, "file_list": [{"fileid": file_id, "max_age": 7200}] } response = requests.post(download_meta_url, params=params, json=payload, verify=False).json() if response.get('errcode', 0) != 0: raise Exception(f"下载元数据获取失败: {response}") file_info = response['file_list'][0] if file_info['status'] != 0: raise Exception(f"下载错误: {file_info['errmsg']}") download_resp = requests.get(file_info['download_url'], verify=False) if download_resp.status_code != 200: raise Exception("文件下载失败") with open(local_path, 'wb') as f: f.write(download_resp.content) return True
if __name__ == "__main__": APPID = "your-wechat-appid" SECRET = "your-wechat-secret" ENV_ID = "your-cloud-env-id" storage = WeChatCloudStorage(APPID, SECRET, ENV_ID) try: file_id = storage.upload_file("../test.png", "image/test2.png") print(f"文件上传成功,File ID: {file_id}") except Exception as e: print(f"上传失败: {e}") try: storage.download_file(file_id, "downloaded_image.jpg") print("文件下载成功") except Exception as e: print(f"下载失败: {e}")
|