Created
April 16, 2016 22:17
-
-
Save rskumar/a0cdc81947997f33876bf7b35c843b97 to your computer and use it in GitHub Desktop.
Mozilla cornice api request validation with Schematics model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf8 | |
from schematics.models import ModelMeta | |
from schematics.exceptions import ModelValidationError | |
def validate_model(model): | |
''' | |
Validate cornice api request against given schematics `model` | |
:param model: Schematics model | |
''' | |
if not isinstance(model, ModelMeta): | |
raise Exception("model should be schematics model class") | |
def validate(request): | |
json_body = {} | |
try: | |
json_body = request.json_body | |
except Exception as ex: | |
# request.errors.add('body', None, 'Invalid request json') | |
pass | |
m = model(json_body) | |
# Perform model validation | |
try: | |
m.validate() | |
except ModelValidationError as validation_exc: | |
for k, v in validation_exc.messages.items(): | |
request.errors.add('body', k, v) | |
return validate | |
# Usage | |
from cornice.service import Service | |
from schematics.models import Model | |
from schematics.types import StringType, BooleanType | |
# Define schema | |
class Category(Model): | |
name = StringType(required=True, min_length=3, max_length=100) | |
published = BooleanType(default=False) | |
# Define cornice api | |
category_coll_api = Service('category_coll_api_v1', path='/api/v1/category', renderer='json') | |
@category_coll_api.post(validators=[validate_model(Category)], http_cache=None) | |
def create_category(request): | |
pass | |
# This will fail for request with improper data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment