|
| 1 | +import logging |
| 2 | +from typing import cast |
| 3 | +from uuid import uuid4 |
| 4 | + |
| 5 | +from aiohttp import web |
| 6 | +from asyncpg import Connection |
| 7 | +from file_storage.sql import ( |
| 8 | + insert_meta_query, |
| 9 | + retrieve_data_by_uuid, |
| 10 | + upload_data_query, |
| 11 | +) |
| 12 | +from file_storage.typings import AioHttpApplication |
| 13 | +from pydantic import UUID4 |
| 14 | + |
| 15 | + |
| 16 | +class FileStorageHandler: |
| 17 | + logger = logging.getLogger("FileStorageHandler") |
| 18 | + |
| 19 | + @classmethod |
| 20 | + async def put(cls, request: web.Request): |
| 21 | + """Upload action handler.""" |
| 22 | + app: AioHttpApplication = cast(AioHttpApplication, request.app) |
| 23 | + insert_data_query = upload_data_query() |
| 24 | + payload = await request.read() |
| 25 | + conn: Connection |
| 26 | + async with app.db.acquire() as conn: |
| 27 | + async with conn.transaction(): |
| 28 | + uploaded_file = await conn.fetchrow(insert_data_query, payload) |
| 29 | + file_hash = uploaded_file["hash"] |
| 30 | + file_uuid = str(uuid4()) |
| 31 | + cls.logger.info( |
| 32 | + f"File hash: {file_hash}, file_uuid: {file_uuid}" |
| 33 | + ) |
| 34 | + await conn.execute( |
| 35 | + insert_meta_query(), |
| 36 | + file_uuid, |
| 37 | + request.content_type, |
| 38 | + file_hash, |
| 39 | + ) |
| 40 | + return web.json_response( |
| 41 | + {"link": str(request.rel_url / file_uuid)}, |
| 42 | + status=web.HTTPCreated.status_code, |
| 43 | + ) |
| 44 | + |
| 45 | + @classmethod |
| 46 | + async def get(cls, request: web.Request): |
| 47 | + """Get file from storage by UUID.""" |
| 48 | + try: |
| 49 | + uuid = UUID4(request.match_info["uuid"]) |
| 50 | + except ValueError: |
| 51 | + raise web.HTTPBadRequest |
| 52 | + app: AioHttpApplication = cast(AioHttpApplication, request.app) |
| 53 | + conn: Connection |
| 54 | + query = retrieve_data_by_uuid() |
| 55 | + async with app.db.acquire() as conn: |
| 56 | + data = await conn.fetchrow(query, uuid) |
| 57 | + if not data: |
| 58 | + raise web.HTTPNotFound |
| 59 | + return web.Response( |
| 60 | + body=data["data"], content_type=data["content_type"] |
| 61 | + ) |
0 commit comments