3

In the python-eve REST API framework I define a list in a resource, the type of the list item is dict. And I don't want the list to be empty. So, how to define the schema?

{
    'parents' : {
        'type' : 'list',
        'schema' : {
            'parent' : 'string'
        }
    }
}
Nicola Iarocci
  • 6,606
  • 1
  • 20
  • 33

2 Answers2

2

Currently the empty validation rule is only available for string types, but you can subclass the standard validator to make it capable of processing lists:

from eve.io.mongo import Validator

class MyValidator(Validator):
    def _validate_empty(self, empty, field, value):
        # let the standard validation happen
        super(Validator, self)._validate_empty(empty, field, value)
        # add your custom list validation
        if isinstance(value, list) and len(value) == 0 and not empty:
            self._error(field, "list cannot be empty")

or, if want to provide the standard empty error message instead:

from eve.io.mongo import Validator
from cerberus import errors

class MyValidator(Validator):
    def _validate_empty(self, empty, field, value):
        # let the standard validation happen
        super(Validator, self)._validate_empty(empty, field, value)
        # add your custom list validation
        if isinstance(value, list) and len(value) == 0 and not empty:
            self._error(field, errors.ERROR_EMPTY_NOT_ALLOWED)

Then you run your API like this:

app = Eve(validator=MyValidator)
app.run()

PS: I plan on adding lists and dicts to Cerberus' empty rule sometime in the future.

Nicola Iarocci
  • 6,606
  • 1
  • 20
  • 33
-1

There isn't an inbuilt way to do this. You could define a wrapper class for your list though:

class ListWrapper(list):
    # Constructor
    __init__(self, **kwargs):
        allIsGood = False
        # 'kwargs' is a dict with all your 'argument=value' pairs
        # Check if all arguments are given & set allIsGood
        if not allIsGood:
            raise ValueError("ListWrapper doesn't match schema!")
        else:
            # Call the list's constructor, i.e. the super constructor
            super(ListWrapper, self).__init__()

            # Manipulate 'self' as you please

Use ListWrapper wherever you need your non-empty list. You could externalize the definition of the schema somehow if you'd like and add it as an input to the constructor.

Also: You might want to take a look at this

Community
  • 1
  • 1
Tejas Pendse
  • 551
  • 6
  • 19
  • Do you mean to define a Custom Validation Rules like http://python-eve.org/validation.html#custom-validation-rules – user3583796 May 16 '14 at 14:37
  • No I didn't because I didn't want to use external packages. You can add a `Validator` to validate your fields if you're using eve. – Tejas Pendse May 16 '14 at 14:43