You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
With the new validation API in #376, it is now possible to have schemas that validate things accross different parts of the request (e.g. querystring/headers/body). This is very convenient and powerful but can be tedious if you only need to validate body payloads because you have to define schemas like this:
diff --git a/cornice/validators/_colander.py b/cornice/validators/_colander.py
index 5136dca..ba83424 100644
--- a/cornice/validators/_colander.py+++ b/cornice/validators/_colander.py@@ -1,12 +1,28 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
-from colander import Invalid+import colander++from cornice.validators import extract_cstruct+++def _body_deserializer(request):+ request_data = extract_cstruct(request)+ return request_data['body']+++def body_validator(request, **kwargs):+ schema = kwargs.get('schema')+ if schema is not None:+ request_schema = colander.MappingSchema()+ request_schema.add('body', schema())+ kwargs['schema'] = request_schema+ kwargs['deserializer'] = _body_deserializer+ return validator(request, **kwargs)
def validator(request, deserializer=None, **kw):
if deserializer is None:
- from cornice.validators import extract_cstruct
deserializer = extract_cstruct
schema = kw.get('schema')
@@ -19,7 +35,7 @@ def validator(request, deserializer=None, **kw):
try:
deserialized = schema.deserialize(cstruct)
request.validated.update(deserialized)
- except Invalid as e:+ except colander.Invalid as e:
translate = request.localizer.translate
error_dict = e.asdict(translate=translate)
for name, msg in error_dict.items():
The text was updated successfully, but these errors were encountered:
With the new validation API in #376, it is now possible to have schemas that validate things accross different parts of the request (e.g. querystring/headers/body). This is very convenient and powerful but can be tedious if you only need to validate body payloads because you have to define schemas like this:
We could have a
colander_body_validator
that validates the body only, which would prevent having to define a upper level schema:The code is short and would look like this:
The text was updated successfully, but these errors were encountered: