Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to validate list using marshmallow?

Tags:

Is it possible to validate list using marshmallow?

class SimpleListInput(Schema):     items = fields.List(fields.String(), required=True)  # expected invalid type error data, errors = SimpleListInput().load({'some': 'value'})  # should be ok  data, errors = SimpleListInput().load(['some', 'value']) 

Or it is expected to validate only objects?

like image 486
avasin Avatar asked May 15 '16 10:05

avasin


People also ask

What is Python marshmallow used for?

Marshmallow is a Python library that converts complex data types to and from Python data types. It is a powerful tool for both validating and converting data.

What are marshmallow schemas?

In short, marshmallow schemas can be used to: Validate input data. Deserialize input data to app-level objects. Serialize app-level objects to primitive Python types. The serialized objects can then be rendered to standard formats such as JSON for use in an HTTP API.


2 Answers

To validate top-level lists, you need to instantiate your list item schema with many=True argument.

Example:

class UserSchema(marshmallow.Schema):     name = marshmallow.fields.String()  data, errors = UserSchema(many=True).load([     {'name': 'John Doe'},     {'name': 'Jane Doe'} ]) 

But it still needs to be an object schema, Marshmallow does not support using top-level non-object lists. In case you need to validate top-level list of non-object types, a workaround would be to define a schema with one List field of your types and just wrap payload as if it was an object:

class SimpleListInput(marshmallow.Schema):     items = marshmallow.fields.List(marshmallow.fields.String(), required=True)  payload = ['foo', 'bar'] data, errors = SimpleListInput().load({'items': payload}) 
like image 83
Maxim Kulkin Avatar answered Oct 04 '22 04:10

Maxim Kulkin


SimpleListInput is a class with a property "items". The property "items" is who accepts a list of strings.

>>> data, errors = SimpleListInput().load({'items':['some', 'value']}) >>> print data, errors {'items': [u'some', u'value']}  {} >>> data, errors = SimpleListInput().load({'items':[]}) >>> print data, errors {'items': []}  {} >>> data, errors = SimpleListInput().load({}) >>> print data, errors {}  {'items': [u'Missing data for required field.']} 

If you want a custom validate, for example, not accept an empty list in "items":

from marshmallow import fields, Schema, validates, ValidationError  class SimpleListInput(Schema):     items = fields.List(fields.String(), required=True)      @validates('items')     def validate_length(self, value):         if len(value) < 1:             raise ValidationError('Quantity must be greater than 0.')  

Then...

>>> data, errors = SimpleListInput().load({'items':[]}) >>> print data, errors {'items': []}  {'items': ['Quantity must be greater than 0.']} 

Take a look at Validation

UPDATE:

As @Turn commented below. You can do this:

from marshmallow import fields, Schema, validate  class SimpleListInput(Schema):             items = fields.List(fields.String(), required=True, validate=validate.Length(min=1)) 
like image 29
Jair Perrut Avatar answered Oct 04 '22 05:10

Jair Perrut