forked from mtusi2026/mtusi2026lab5
Grade 4
This commit is contained in:
+10
-7
@@ -6,7 +6,7 @@ from PIL import Image, UnidentifiedImageError
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .errors import APIError
|
||||
from .models import Attachment, ChatMember
|
||||
from .models import Attachment, AttachmentJob, ChatMember
|
||||
from .object_storage import BUCKET, PREFIX, s3_client
|
||||
from .store import ensure_uuid, serialize, store
|
||||
|
||||
@@ -48,25 +48,28 @@ def lock_object(session, key):
|
||||
|
||||
def metadata(attachment):
|
||||
result = serialize(attachment, 'id', 'chat_id', 'owner_id', 'filename',
|
||||
'content_type', 'size_bytes', 'sha256', 'created_at')
|
||||
return {**result, 'updated_at': result['created_at'], 'status': 'ready',
|
||||
'variants': [], 'error_code': None}
|
||||
'content_type', 'size_bytes', 'sha256', 'created_at',
|
||||
'updated_at', 'status', 'error_code')
|
||||
return {**result, 'variants': [{k: v for k, v in item.items() if k != 'object_key'}
|
||||
for item in attachment.variants]}
|
||||
|
||||
|
||||
def save_attachment(source, chat_id, actor_id, filename, content_type, size, digest):
|
||||
validate_image(source, content_type)
|
||||
attachment_id = str(uuid4())
|
||||
key = PREFIX + attachment_id
|
||||
staging_key = 'staging/' + attachment_id
|
||||
with store.sessions.begin() as session:
|
||||
store._chat(session, chat_id, actor_id)
|
||||
lock_object(session, key)
|
||||
s3_client().put_object(Bucket=BUCKET, Key=key, Body=source,
|
||||
lock_object(session, staging_key)
|
||||
s3_client().put_object(Bucket=BUCKET, Key=staging_key, Body=source,
|
||||
ContentLength=size, ContentType=content_type)
|
||||
attachment = Attachment(id=attachment_id, chat_id=chat_id, owner_id=actor_id,
|
||||
object_key=key, filename=filename, content_type=content_type,
|
||||
size_bytes=size, sha256=digest)
|
||||
size_bytes=size, sha256=digest, staging_key=staging_key)
|
||||
session.add(attachment)
|
||||
session.flush()
|
||||
session.add(AttachmentJob(attachment_id=attachment_id))
|
||||
result = metadata(attachment)
|
||||
# An uncertain COMMIT is not followed by DELETE: cleanup checks the DB later.
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user