forked from mtusi2026/mtusi2026lab5
Add 4 lab code
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
from tempfile import TemporaryFile
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
from starlette.responses import StreamingResponse
|
||||
|
||||
from ..attachments import MAX_BYTES, get_attachment, metadata, save_attachment, validate_filename
|
||||
from ..dependencies import current_user
|
||||
from ..errors import APIError
|
||||
from ..object_storage import BUCKET, s3_client
|
||||
from ..store import ensure_uuid, store
|
||||
|
||||
router = APIRouter(prefix='/api/v1', tags=['attachments'])
|
||||
# At most one decoded image (<=40M pixels) per API process; incoming bodies use disk.
|
||||
decode_slot = asyncio.Semaphore(1)
|
||||
|
||||
|
||||
@router.post('/chats/{chat_id}/attachments', status_code=201)
|
||||
async def upload(chat_id: str, request: Request, filename: str = Query(...),
|
||||
user: dict = Depends(current_user)):
|
||||
chat_id = ensure_uuid(chat_id)
|
||||
await run_in_threadpool(store.get_chat_for_user, chat_id, user['id'])
|
||||
validate_filename(filename)
|
||||
content_type = request.headers.get('content-type', '').split(';', 1)[0].strip().lower()
|
||||
if content_type not in ('image/png', 'image/jpeg'):
|
||||
raise APIError(415, 'unsupported_media_type', 'Ожидается PNG или JPEG')
|
||||
length = request.headers.get('content-length')
|
||||
if length is not None:
|
||||
try:
|
||||
length = int(length)
|
||||
if length < 0:
|
||||
raise ValueError()
|
||||
except ValueError as exc:
|
||||
raise APIError(400, 'invalid_request', 'Неверный Content-Length') from exc
|
||||
if length > MAX_BYTES:
|
||||
raise APIError(413, 'payload_too_large', 'Файл слишком большой')
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
with TemporaryFile() as source:
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise APIError(413, 'payload_too_large', 'Файл слишком большой')
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(source.write, chunk)
|
||||
except (TimeoutError, ClientDisconnect) as exc:
|
||||
raise APIError(400, 'invalid_request', 'Загрузка прервана') from exc
|
||||
if length is not None and size != length:
|
||||
raise APIError(400, 'invalid_request', 'Неполное тело запроса')
|
||||
async with decode_slot:
|
||||
return await run_in_threadpool(save_attachment, source, chat_id, user['id'],
|
||||
filename, content_type, size, digest.hexdigest())
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}')
|
||||
def attachment_info(attachment_id: str, user: dict = Depends(current_user)):
|
||||
return metadata(get_attachment(attachment_id, user['id']))
|
||||
|
||||
|
||||
@router.get('/attachments/{attachment_id}/content')
|
||||
def download(attachment_id: str, variant: str = 'original', user: dict = Depends(current_user)):
|
||||
attachment = get_attachment(attachment_id, user['id'])
|
||||
if variant != 'original':
|
||||
raise APIError(404, 'not_found', 'Вариант не найден')
|
||||
body = s3_client().get_object(Bucket=BUCKET, Key=attachment.object_key)['Body']
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
yield from body.iter_chunks(chunk_size=64 * 1024)
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
return StreamingResponse(chunks(), media_type=attachment.content_type,
|
||||
headers={'Content-Length': str(attachment.size_bytes),
|
||||
'Content-Disposition': "attachment; filename*=UTF-8''" + quote(attachment.filename, safe=''),
|
||||
'X-Content-Type-Options': 'nosniff'},
|
||||
background=BackgroundTask(body.close))
|
||||
Reference in New Issue
Block a user