Source code for luna_faces.app.handlers.attributes_handler
"""
Module realized a handler for creating and getting new temporary attributes
"""
import asyncio
from typing import List, Union
from uuid import uuid4
from sanic.response import HTTPResponse
from app.handlers.base_handler import AttributesBaseRequestHandler
from app.handlers.query_validators import listItemsCheckerFactory, ttlGetter
from app.version import VERSION
from attributes_db.model import TemporaryAttributes
from crutches_on_wheels.errors.errors import Error
from crutches_on_wheels.errors.exception import VLException
from crutches_on_wheels.maps.vl_maps import TEMPORARY_ATTRIBUTE_TARGET_MAP
from crutches_on_wheels.web.query_getters import listUUIDsGetter, uuidGetter
[docs]class AttributesHandler(AttributesBaseRequestHandler):
"""
Handler for work with attributes
Resource: "/{api_version}/attributes"
"""
[docs] async def get(self) -> HTTPResponse:
"""
Get several temporary attributes. See `spec_get_attributes`_.
.. _spec_get_attributes:
_static/api.html#operation/getAttributes
Returns:
response json with attributes
"""
accountId = self.getQueryParam("account_id", uuidGetter)
attributeIds = self.getQueryParam("attribute_ids", listUUIDsGetter, require=True)
targets = self.getQueryParam(
"targets",
listItemsCheckerFactory(list(TEMPORARY_ATTRIBUTE_TARGET_MAP)),
default=list(TEMPORARY_ATTRIBUTE_TARGET_MAP),
)
descriptorVersion = self.getQueryParam(
"descriptor_version", int, default=self.config.defaultFaceDescriptorVersion
)
futures = (self.attributesContext.get(attrId, accountId=accountId) for attrId in attributeIds)
results: List[Union[TemporaryAttributes, VLException, Exception]] = await asyncio.gather(
*futures, return_exceptions=True
)
attributes = []
for result in results:
if isinstance(result, VLException):
if result.error == Error.AttributesNotFound:
continue
raise result
if isinstance(result, Exception):
raise result
attributes.append(self.makeOutputAttribute(result, targets=targets, descriptorVersion=descriptorVersion))
return self.success(outputJson={"attributes": attributes})
[docs] async def post(self) -> HTTPResponse:
"""
Create new temporary attribute. See `spec_create_new_attribute`_.
.. _spec_create_new_attribute:
_static/api.html#operation/createAttribute
Returns:
response json with attribute id
"""
attributeId = str(uuid4())
attribute = await self.getInputAttribute(attributeId)
ttl = self.getQueryParam(
"ttl",
lambda value: ttlGetter(value, self.config.attributesStorageSettings.maxTTL),
default=self.config.attributesStorageSettings.defaultTTL,
)
await self.attributesContext.put(attribute, ttl)
url = "/{}/attributes/{}".format(VERSION["Version"]["api"], attribute.attributeId)
self.respHeaders["Location"] = url
return self.success(201, outputJson={"attribute_id": attribute.attributeId, "url": url})