forked from mtusi2026/mtusi2026lab6
Перенести реализацию лабораторной 5
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.attachments import AttachmentService
|
||||
from ..deps import attachment_service, current_user
|
||||
from ..schemas import AttachmentOut
|
||||
|
||||
router = APIRouter(tags=['attachments'])
|
||||
|
||||
|
||||
@router.post(
|
||||
'/api/v1/chats/{chat_id}/attachments',
|
||||
status_code=202,
|
||||
response_model=AttachmentOut,
|
||||
)
|
||||
async def upload(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
content_type: Annotated[str | None, Header(alias='Content-Type')] = None,
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> AttachmentOut:
|
||||
attachment = await attachments.upload(
|
||||
actor,
|
||||
chat_id,
|
||||
filename,
|
||||
content_type or '',
|
||||
request.stream(),
|
||||
)
|
||||
return AttachmentOut.from_domain(attachment)
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}', response_model=AttachmentOut)
|
||||
async def metadata(
|
||||
attachment_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> AttachmentOut:
|
||||
return AttachmentOut.from_domain(await attachments.get(actor, attachment_id))
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}/content')
|
||||
async def content(
|
||||
attachment_id: UUID,
|
||||
variant: str = Query('original'),
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> StreamingResponse:
|
||||
attachment, stream, content_type, size_bytes = await attachments.content(
|
||||
actor, attachment_id, variant
|
||||
)
|
||||
return StreamingResponse(
|
||||
stream.chunks(),
|
||||
media_type=content_type,
|
||||
headers={
|
||||
'Content-Length': str(size_bytes),
|
||||
'Content-Disposition': f'inline; filename="attachment-{attachment.id}"',
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user