2024-09-10 09:19:47 +08:00
|
|
|
from collections.abc import Generator
|
|
|
|
|
|
|
|
import tos
|
|
|
|
|
2024-10-22 11:01:32 +08:00
|
|
|
from configs import dify_config
|
2024-09-10 09:19:47 +08:00
|
|
|
from extensions.storage.base_storage import BaseStorage
|
|
|
|
|
|
|
|
|
2024-10-09 14:15:27 +08:00
|
|
|
class VolcengineTosStorage(BaseStorage):
|
2024-09-10 09:19:47 +08:00
|
|
|
"""Implementation for Volcengine TOS storage."""
|
|
|
|
|
2024-10-22 11:01:32 +08:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.bucket_name = dify_config.VOLCENGINE_TOS_BUCKET_NAME
|
2024-09-10 09:19:47 +08:00
|
|
|
self.client = tos.TosClientV2(
|
2024-10-22 11:01:32 +08:00
|
|
|
ak=dify_config.VOLCENGINE_TOS_ACCESS_KEY,
|
|
|
|
sk=dify_config.VOLCENGINE_TOS_SECRET_KEY,
|
|
|
|
endpoint=dify_config.VOLCENGINE_TOS_ENDPOINT,
|
|
|
|
region=dify_config.VOLCENGINE_TOS_REGION,
|
2024-09-10 09:19:47 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
def save(self, filename, data):
|
|
|
|
self.client.put_object(bucket=self.bucket_name, key=filename, content=data)
|
|
|
|
|
|
|
|
def load_once(self, filename: str) -> bytes:
|
|
|
|
data = self.client.get_object(bucket=self.bucket_name, key=filename).read()
|
|
|
|
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)
|
|
|
|
while chunk := response.read(4096):
|
|
|
|
yield chunk
|
2024-09-10 09:19:47 +08:00
|
|
|
|
|
|
|
def download(self, filename, target_filepath):
|
|
|
|
self.client.get_object_to_file(bucket=self.bucket_name, key=filename, file_path=target_filepath)
|
|
|
|
|
|
|
|
def exists(self, filename):
|
|
|
|
res = self.client.head_object(bucket=self.bucket_name, key=filename)
|
|
|
|
if res.status_code != 200:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def delete(self, filename):
|
|
|
|
self.client.delete_object(bucket=self.bucket_name, key=filename)
|