clearml-server/apiserver/apimodels/base.py

70 lines
1.9 KiB
Python
Raw Normal View History

2019-06-10 21:24:35 +00:00
from jsonmodels import models, fields
from jsonmodels.validators import Length
2019-06-10 21:24:35 +00:00
from mongoengine.base import BaseDocument
2021-01-05 14:28:49 +00:00
from apiserver.apimodels import DictField, ListField
2019-06-10 21:24:35 +00:00
class MongoengineFieldsDict(DictField):
"""
DictField representing mongoengine field names/value mapping.
Used to convert mongoengine-style field/subfield notation to user-presentable syntax, including handling update
operators.
"""
mongoengine_update_operators = (
"inc",
"dec",
"push",
"push_all",
"pop",
"pull",
"pull_all",
"add_to_set",
2019-06-10 21:24:35 +00:00
)
@staticmethod
def _normalize_mongo_value(value):
if isinstance(value, BaseDocument):
return value.to_mongo()
return value
@classmethod
def _normalize_mongo_field_path(cls, path, value):
parts = path.split("__")
2019-06-10 21:24:35 +00:00
if len(parts) > 1:
if parts[0] == "set":
2019-06-10 21:24:35 +00:00
parts = parts[1:]
elif parts[0] == "unset":
2019-06-10 21:24:35 +00:00
parts = parts[1:]
value = None
elif parts[0] in cls.mongoengine_update_operators:
return None, None
return ".".join(parts), cls._normalize_mongo_value(value)
2019-06-10 21:24:35 +00:00
def parse_value(self, value):
value = super(MongoengineFieldsDict, self).parse_value(value)
return {
k: v
for k, v in (self._normalize_mongo_field_path(*p) for p in value.items())
if k is not None
}
class UpdateResponse(models.Base):
updated = fields.IntField(required=True)
fields = MongoengineFieldsDict()
class PagedRequest(models.Base):
page = fields.IntField()
page_size = fields.IntField()
2019-12-29 07:03:19 +00:00
class IdResponse(models.Base):
id = fields.StringField(required=True)
class MakePublicRequest(models.Base):
ids = ListField(items_types=str, validators=[Length(minimum_value=1)])