import os from qcloud_cos import CosConfig, CosS3Client class TencentCosStorageService: def __init__(self, secret_id: str, secret_key: str, region: str, bucket: str, base_url: str): self.bucket = bucket self.base_url = base_url.rstrip("/") config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key) self.client = CosS3Client(config) def upload_bytes(self, image_bytes: bytes, key: str, content_type: str) -> str: self.client.put_object( Bucket=self.bucket, Body=image_bytes, Key=key, ContentType=content_type, ) return f"{self.base_url}/{key}" @classmethod def from_env(cls) -> "TencentCosStorageService": return cls( secret_id=os.getenv("TENCENT_COS_SECRET_ID", ""), secret_key=os.getenv("TENCENT_COS_SECRET_KEY", ""), region=os.getenv("TENCENT_COS_REGION", ""), bucket=os.getenv("TENCENT_COS_BUCKET", ""), base_url=os.getenv("TENCENT_COS_BASE_URL", ""), )