Search code examples
evecerberus

Force Eve to validate document inside custom route


In my python/eve REST API I have a custom route that does some non trivial processing. I'm receiving a POST request and after some processing I'll send this doc to database. But it would be nice if I could validate this doc using the same validation used by Eve. I know I can use cerberus directly but it does not handle things like data_relation which I have in my schema.

There is any way I can invoke the internal Eve validator?


Solution

  • You could use the default Validator (or your own subclass if you customised it). The following example snippet uses a database hook (documents are processed just before db insertion).

    from eve.io.mongo import Validator
    from flask import current_app
    
    validator = Validator()
    
    def on_insert(resource, documents):        
        schema = current_app.config['DOMAIN'][resource]['schema']
        for document in items:
            if not validator(document):
                print validator.errors
    
    
    app = Eve()
    app.on_insert += on_insert
    
    if __name__ == '__main__':
        app.run()
    

    Now, this example would return errors on every single document since, at this stage, they include automatic fields such as _created and _updated, which are not included in the schema, but you get the idea (you could circumvent this issue by setting allow_unknown property for the validator instance).