from pathlib import Path from typing import BinaryIO from uuid import uuid4 from aioshutil import copyfileobj from barcodes.images_uploader.base import BaseImagesUploader from constants import APP_PATH, API_ROOT class BarcodeImagesUploader(BaseImagesUploader): def __init__(self): self.relative_path = Path("static/images/product_barcodes") self.storage_path = APP_PATH / self.relative_path if not Path.exists(self.storage_path): Path.mkdir(self.storage_path) def get_url(self, filename: str) -> str: file_location = self.relative_path / filename return f"{API_ROOT}/{file_location}" def get_abs_path(self, filename: str) -> str: file_location = self.storage_path / filename return file_location def delete(self, filename: str): file_location = self.storage_path / filename if file_location.exists(): file_location.unlink() async def upload(self, file: BinaryIO, filename: str) -> str: filename = str(uuid4()) + '.' + filename.split('.')[-1] file_location = self.storage_path / filename with open(file_location, 'wb') as buffer: await copyfileobj(file, buffer) return filename