Files
FileCodeBox/storage.py
T

61 lines
1.7 KiB
Python
Raw Permalink Normal View History

2022-12-12 11:18:55 +08:00
import os
import asyncio
2022-12-13 12:45:28 +08:00
from datetime import datetime
2022-12-12 11:18:55 +08:00
from pathlib import Path
2022-12-13 12:45:28 +08:00
from typing import BinaryIO
from fastapi import UploadFile
2022-12-12 11:18:55 +08:00
import settings
class FileSystemStorage:
DATA_ROOT = Path(settings.DATA_ROOT)
STATIC_URL = settings.STATIC_URL
NAME = "filesystem"
2022-12-13 12:45:28 +08:00
async def get_filepath(self, text: str):
return self.DATA_ROOT / text.lstrip(self.STATIC_URL + '/')
2022-12-12 11:18:55 +08:00
2022-12-13 12:45:28 +08:00
async def get_text(self, file: UploadFile, key: str):
2022-12-12 11:18:55 +08:00
ext = file.filename.split('.')[-1]
2022-12-13 12:45:28 +08:00
now = datetime.now()
path = self.DATA_ROOT / f"upload/{now.year}/{now.month}/{now.day}/"
2022-12-12 11:18:55 +08:00
if not path.exists():
path.mkdir(parents=True)
2022-12-13 21:16:41 +08:00
text = f"{self.STATIC_URL}/{(path / f'{key}.{ext}').relative_to(self.DATA_ROOT)}"
2022-12-12 11:18:55 +08:00
return text
2022-12-13 17:50:22 +08:00
@staticmethod
async def get_size(file: UploadFile):
2022-12-13 12:45:28 +08:00
f = file.file
f.seek(0, os.SEEK_END)
size = f.tell()
f.seek(0, os.SEEK_SET)
return size
2022-12-13 17:50:22 +08:00
@staticmethod
def _save(filepath, file: BinaryIO):
2022-12-13 12:45:28 +08:00
with open(filepath, 'wb') as f:
chunk_size = 256 * 1024
chunk = file.read(chunk_size)
while chunk:
f.write(chunk)
chunk = file.read(chunk_size)
async def save_file(self, file: UploadFile, text: str):
filepath = await self.get_filepath(text)
await asyncio.to_thread(self._save, filepath, file.file)
2022-12-13 14:18:02 +08:00
async def delete_file(self, text: str):
filepath = await self.get_filepath(text)
await asyncio.to_thread(os.remove, filepath)
2022-12-12 15:15:17 +08:00
2022-12-13 14:18:02 +08:00
async def delete_files(self, texts):
tasks = [self.delete_file(text) for text in texts]
await asyncio.gather(*tasks)
2022-12-12 11:18:55 +08:00
STORAGE_ENGINE = {
"filesystem": FileSystemStorage
2022-12-12 15:15:17 +08:00
}