Добавить определенные ограничения на поля схемы зефира - PullRequest
0 голосов
/ 26 июня 2019

Я пытаюсь использовать зефир для проверки некоторых данных JSON и получения наилучшего объекта. Давайте посмотрим код ниже

class PublicationAuthorsSchema(Schema):
    name = fields.String()
    role = fields.String(validate=OneOf(choices=['author', 'inventor']))

class PublicationSchema(Schema):
    authors = fields.List(fields.Nested(PublicationAuthorSchema))
    title = fields.String()

class BookSchema(PublicationSchema):
    # Something here i would like to limit authors role to 'author' value
    publisher = fields.String()

class PatentSchema(PublicationSchema):
    # Something here i would like to limit authors role to 'inventor' value
    country_restrictions = fields.List(fields.String)

...

def publication_loader(json_data):
  schema_class = PublicationSchema
  if json_data.get('$schema') == 'http://example.org/patent_v1.0.0.json':
    schema_class = PatentSchema
  elif json_data.get('$schema') == 'http://example.org/book_v1.0.0.json':
    schema_class = BookSchema

  schema = schema_class()
  # I tried to alter schema here ... 
  result = schema.load(json_data)
  if result.errors:
    raise MarshmallowError(result.errors)
  return result.data 

...

data = {
  '$schema': 'http://example.org/book_v1.0.0.json',
  'title': 'Programming with python',
  'authors': [
    {
      'name': 'John Doe',
      'role': 'author'
    },{
      'name': 'Harvey Smith',
      'role': 'inventor'
    }
  ]
}
result = publication_loader(data)
#  I would like than a ValidationError will be raised because, authors of 'book' could only have 'author' role
#  The Author 'Harvey Smith' should be in error because he is tagged as 'inventor' (stupid example, i admit it)

Я уже пытался использовать декораторы @pre_load и @validates_schema, но, похоже, это не так. Я пытался изменить мой schema_class непосредственно перед загрузкой данных, но та же проблема. Знаете ли вы хороший способ решить эту проблему?

Как всегда, спасибо за помощь

Renaud

...