Skip to content

Commit

Permalink
Merge pull request #424 from gabisurita/support-json-merge
Browse files Browse the repository at this point in the history
Add custom JSON content-type support
  • Loading branch information
leplatrem committed Dec 15, 2016
2 parents 728240e + a5b0d68 commit 85ce171
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 2 deletions.
5 changes: 5 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ CHANGELOG
2.3.0 (unreleased)
==================

**Enhancements**

- Add support for validation with specific JSON Content-Types
(i.e application/merge-patch+json).

**Bug fixes**

- Fix ``cornice.cors.get_cors_preflight_view`` to make it parse
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Cornice:
* David Charboneau <david@thecharboneaus.net>
* David Grant <seizethedave@gmail.com>
* Elias <elias@stupeflix.com>
* Gabriela Surita <gsurita@mozilla.com>
* Gael Pasgrimaud <gael@gawel.org>
* George V. Reilly <george@reilly.org>
* Graham Higgins <gjh-github@bel-epa.com>
Expand Down
7 changes: 5 additions & 2 deletions cornice/validators/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# 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/.
import re

from webob.multidict import MultiDict
from cornice.validators._colander import (
validator as colander_validator,
Expand Down Expand Up @@ -30,10 +32,11 @@ def extract_cstruct(request):
:returns: A mapping containing most request attributes.
:rtype: dict
"""
is_json = re.match('^application/(.*?)json$', str(request.content_type))

if request.content_type == 'application/x-www-form-urlencoded':
body = request.POST.mixed()

elif request.content_type and request.content_type != 'application/json':
elif request.content_type and not is_json:
body = request.body
else:
if request.body:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,15 @@ def test_valid_json(self):
})
self.assertEqual(response.json['username'], 'man')

def test_valid_nonstandard_json(self):
app = self.make_ordinary_app()
response = app.post_json(
'/signup',
{'username': 'man'},
headers={'content-type': 'application/merge-patch+json'}
)
self.assertEqual(response.json['username'], 'man')

def test_invalid_json(self):
app = self.make_ordinary_app()
response = app.post('/signup',
Expand Down

0 comments on commit 85ce171

Please sign in to comment.