Source code for luna_configurator.app.handlers.setting_handler
# -*- coding: utf-8 -*-
"""Setting Handler
Module realize setting handler.
"""
from typing import Callable
import fastjsonschema
from sanic.response import HTTPResponse
from app.handlers.base_handler import BaseRequestHandler
from app.handlers.functions import intifyId
from app.version import VERSION
from crutches_on_wheels.errors.errors import Error
from crutches_on_wheels.errors.exception import VLException
from db.functions import inputSetting
[docs]class SettingHandler(BaseRequestHandler):
"""
Handler to work with exact setting.
"""
[docs] @intifyId
async def get(self, settingId: int) -> HTTPResponse:
"""
Request to get exact setting. See `spec getSetting`_.
.. _`spec getSetting`:
_static/api.html#operation/getSetting
"""
setting = await self.dbContext.getSetting(settingId)
return self.success(outputJson=setting)
[docs] async def checkSettingDefault(self, settingId, inputTags) -> None:
"""
Check whether setting tags must/must not exist.
Args:
settingId: setting id
inputTags: tags from input json
Raises:
VLException(BadInputJson) if incorrect input tags
"""
existingSetting = await self.dbContext.getSetting(settingId, raiseError=False)
if existingSetting is not None and existingSetting["is_default"]:
if inputTags:
raise VLException(
Error.BadInputJson.format("tags", "'tags' must be empty for the default setting"),
400,
isCriticalError=False,
)
else:
if not inputTags:
raise VLException(
Error.BadInputJson.format("tags", "'tags' must be specified for a non-default setting"),
400,
isCriticalError=False,
)
[docs] async def getUpdSettingSchema(self, settingName: str) -> Callable[[dict], None]:
"""
Get validation schema for update setting
Args:
settingName: setting name
Returns:
validation schema for update setting
"""
return fastjsonschema.compile((await self.getSettingSchema(settingName)))
[docs] @intifyId
async def put(self, settingId: int) -> HTTPResponse:
"""
Request to rewrite setting. See `spec replaceSetting`_.
.. _`spec replaceSetting`:
_static/api.html#operation/replaceSetting
"""
settingDict = self.request.json
settingName = settingDict.get("name", None)
if not isinstance(settingName, str):
raise VLException(Error.BadInputJson.format("name", "'name' must be string"), 400, False)
else:
if settingName in (await self.dbContext.getAllSettingNames()):
self.validateJson(settingDict, (await self.getUpdSettingSchema(settingName)), useJsonSchema=False)
else:
raise VLException(Error.LimitationNotFound.format(settingName), 400, False)
await self.checkSettingDefault(settingId, settingDict.get("tags"))
newSetting = inputSetting(settingDict)
await self.dbContext.replaceSetting(settingId, **newSetting)
self.respHeaders = {"Location": "/{}/settings/{}".format(VERSION["Version"]["api"], settingId)}
return self.success(200, outputJson={"setting_id": settingId})
[docs] @intifyId
async def delete(self, settingId: int) -> HTTPResponse:
"""
Request to remove setting. See `spec deleteSetting`_.
.. _`spec deleteSetting`:
_static/api.html#operation/deleteSetting
"""
setting = await self.dbContext.getSetting(settingId)
if setting["is_default"]:
raise VLException(Error.CannotRemoveDefaultSetting.format(setting["name"]), 423, False)
await self.dbContext.deleteSetting(settingId)
return self.success(204)