- 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
35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from fastapi.encoders import jsonable_encoder
|
|
from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError
|
|
from fastapi.utils import is_body_allowed_for_status_code
|
|
from fastapi.websockets import WebSocket
|
|
from starlette.exceptions import HTTPException
|
|
from starlette.requests import Request
|
|
from starlette.responses import JSONResponse, Response
|
|
from starlette.status import WS_1008_POLICY_VIOLATION
|
|
|
|
|
|
async def http_exception_handler(request: Request, exc: HTTPException) -> Response:
|
|
headers = getattr(exc, "headers", None)
|
|
if not is_body_allowed_for_status_code(exc.status_code):
|
|
return Response(status_code=exc.status_code, headers=headers)
|
|
return JSONResponse(
|
|
{"detail": exc.detail}, status_code=exc.status_code, headers=headers
|
|
)
|
|
|
|
|
|
async def request_validation_exception_handler(
|
|
request: Request, exc: RequestValidationError
|
|
) -> JSONResponse:
|
|
return JSONResponse(
|
|
status_code=422,
|
|
content={"detail": jsonable_encoder(exc.errors())},
|
|
)
|
|
|
|
|
|
async def websocket_request_validation_exception_handler(
|
|
websocket: WebSocket, exc: WebSocketRequestValidationError
|
|
) -> None:
|
|
await websocket.close(
|
|
code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())
|
|
)
|