- Create backend/services/image_storage.py with 4 core functions:
- sanitize_filename(): remove unsafe chars, limit to 255 chars, convert to lowercase
- get_unique_filename(): handle collisions with UUID suffix (format: {name}_{uuid8}_{variant}.jpg)
- ensure_image_directories(): create /images/ root and category subdirs on startup
- save_image(): save bytes to /images/{category}/{filename}, returns relative path
- Create comprehensive test suite (22 tests) covering all functionality
- Integrate ensure_image_directories() into FastAPI startup event
- Directory structure: /images/{category}/{filename}
- Collision handling: auto-suffix with UUID if filename exists
- All tests passing, pathlib.Path for safe operations
43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
from __future__ import annotations
|
|
|
|
import typing
|
|
from types import TracebackType
|
|
|
|
|
|
def to_bytes(
|
|
x: str | bytes, encoding: str | None = None, errors: str | None = None
|
|
) -> bytes:
|
|
if isinstance(x, bytes):
|
|
return x
|
|
elif not isinstance(x, str):
|
|
raise TypeError(f"not expecting type {type(x).__name__}")
|
|
if encoding or errors:
|
|
return x.encode(encoding or "utf-8", errors=errors or "strict")
|
|
return x.encode()
|
|
|
|
|
|
def to_str(
|
|
x: str | bytes, encoding: str | None = None, errors: str | None = None
|
|
) -> str:
|
|
if isinstance(x, str):
|
|
return x
|
|
elif not isinstance(x, bytes):
|
|
raise TypeError(f"not expecting type {type(x).__name__}")
|
|
if encoding or errors:
|
|
return x.decode(encoding or "utf-8", errors=errors or "strict")
|
|
return x.decode()
|
|
|
|
|
|
def reraise(
|
|
tp: type[BaseException] | None,
|
|
value: BaseException,
|
|
tb: TracebackType | None = None,
|
|
) -> typing.NoReturn:
|
|
try:
|
|
if value.__traceback__ is not tb:
|
|
raise value.with_traceback(tb)
|
|
raise value
|
|
finally:
|
|
value = None # type: ignore[assignment]
|
|
tb = None
|