dify/api/extensions/storage/local_fs_storage.py

63 lines
2.1 KiB
Python
Raw Normal View History

2024-04-29 18:22:03 +08:00
import os
import shutil
from collections.abc import Generator
from pathlib import Path
2024-04-29 18:22:03 +08:00
from flask import current_app
2024-04-29 18:22:03 +08:00
from configs import dify_config
2024-04-29 18:22:03 +08:00
from extensions.storage.base_storage import BaseStorage
class LocalFsStorage(BaseStorage):
"""Implementation for local filesystem storage."""
2024-04-29 18:22:03 +08:00
def __init__(self):
super().__init__()
folder = dify_config.STORAGE_LOCAL_PATH
2024-04-29 18:22:03 +08:00
if not os.path.isabs(folder):
folder = os.path.join(current_app.root_path, folder)
2024-04-29 18:22:03 +08:00
self.folder = folder
def _build_filepath(self, filename: str) -> str:
"""Build the full file path based on the folder and filename."""
if not self.folder or self.folder.endswith("/"):
return self.folder + filename
2024-04-29 18:22:03 +08:00
else:
return self.folder + "/" + filename
2024-04-29 18:22:03 +08:00
def save(self, filename, data):
filepath = self._build_filepath(filename)
folder = os.path.dirname(filepath)
2024-04-29 18:22:03 +08:00
os.makedirs(folder, exist_ok=True)
Path(os.path.join(os.getcwd(), filepath)).write_bytes(data)
2024-04-29 18:22:03 +08:00
def load_once(self, filename: str) -> bytes:
filepath = self._build_filepath(filename)
if not os.path.exists(filepath):
2024-04-29 18:22:03 +08:00
raise FileNotFoundError("File not found")
return Path(filepath).read_bytes()
2024-04-29 18:22:03 +08:00
def load_stream(self, filename: str) -> Generator:
filepath = self._build_filepath(filename)
if not os.path.exists(filepath):
raise FileNotFoundError("File not found")
with open(filepath, "rb") as f:
while chunk := f.read(4096): # Read in chunks of 4KB
yield chunk
2024-04-29 18:22:03 +08:00
def download(self, filename, target_filepath):
filepath = self._build_filepath(filename)
if not os.path.exists(filepath):
2024-04-29 18:22:03 +08:00
raise FileNotFoundError("File not found")
shutil.copyfile(filepath, target_filepath)
2024-04-29 18:22:03 +08:00
def exists(self, filename):
filepath = self._build_filepath(filename)
return os.path.exists(filepath)
2024-04-29 18:22:03 +08:00
def delete(self, filename):
filepath = self._build_filepath(filename)
if os.path.exists(filepath):
os.remove(filepath)