30 lines
797 B
Python
30 lines
797 B
Python
from __future__ import annotations
|
|
|
|
from typing import Callable
|
|
from uuid import uuid4
|
|
|
|
from django.core.files.base import ContentFile
|
|
from django.core.files.storage import default_storage
|
|
from django.utils import timezone
|
|
|
|
|
|
def save_generated_image(
|
|
image: bytes,
|
|
*,
|
|
url_builder: Callable[[str], str] | None = None,
|
|
request=None,
|
|
) -> str:
|
|
today = timezone.now()
|
|
path = (
|
|
"generated/images/"
|
|
f"{today:%Y/%m/%d}/"
|
|
f"{uuid4().hex}.png"
|
|
)
|
|
saved_path = default_storage.save(path, ContentFile(image))
|
|
url = default_storage.url(saved_path)
|
|
if url_builder is not None and url.startswith("/"):
|
|
return url_builder(url)
|
|
if request is not None and url.startswith("/"):
|
|
return request.build_absolute_uri(url)
|
|
return url
|