2024-06-17 19:18:52 +08:00
|
|
|
from collections.abc import Generator
|
|
|
|
|
|
|
|
from qcloud_cos import CosConfig, CosS3Client
|
|
|
|
|
2024-10-22 11:01:32 +08:00
|
|
|
from configs import dify_config
|
2024-06-17 19:18:52 +08:00
|
|
|
from extensions.storage.base_storage import BaseStorage
|
|
|
|
|
|
|
|
|
2024-10-09 14:15:27 +08:00
|
|
|
class TencentCosStorage(BaseStorage):
|
|
|
|
"""Implementation for Tencent Cloud COS storage."""
|
2024-06-17 19:18:52 +08:00
|
|
|
|
2024-10-22 11:01:32 +08:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
self.bucket_name = dify_config.TENCENT_COS_BUCKET_NAME
|
2024-06-17 19:18:52 +08:00
|
|
|
config = CosConfig(
|
2024-10-22 11:01:32 +08:00
|
|
|
Region=dify_config.TENCENT_COS_REGION,
|
|
|
|
SecretId=dify_config.TENCENT_COS_SECRET_ID,
|
|
|
|
SecretKey=dify_config.TENCENT_COS_SECRET_KEY,
|
|
|
|
Scheme=dify_config.TENCENT_COS_SCHEME,
|
2024-06-17 19:18:52 +08:00
|
|
|
)
|
|
|
|
self.client = CosS3Client(config)
|
|
|
|
|
|
|
|
def save(self, filename, data):
|
|
|
|
self.client.put_object(Bucket=self.bucket_name, Body=data, Key=filename)
|
|
|
|
|
|
|
|
def load_once(self, filename: str) -> bytes:
|
2024-08-15 12:54:05 +08:00
|
|
|
data = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].get_raw_stream().read()
|
2024-06-17 19:18:52 +08:00
|
|
|
return data
|
|
|
|
|
|
|
|
def load_stream(self, filename: str) -> Generator:
|
2024-10-25 10:11:25 +08:00
|
|
|
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
|
|
|
yield from response["Body"].get_stream(chunk_size=4096)
|
2024-06-17 19:18:52 +08:00
|
|
|
|
|
|
|
def download(self, filename, target_filepath):
|
|
|
|
response = self.client.get_object(Bucket=self.bucket_name, Key=filename)
|
2024-08-15 12:54:05 +08:00
|
|
|
response["Body"].get_stream_to_file(target_filepath)
|
2024-06-17 19:18:52 +08:00
|
|
|
|
|
|
|
def exists(self, filename):
|
|
|
|
return self.client.object_exists(Bucket=self.bucket_name, Key=filename)
|
|
|
|
|
|
|
|
def delete(self, filename):
|
|
|
|
self.client.delete_object(Bucket=self.bucket_name, Key=filename)
|