0001-jsondatastore-check-if-request.body-is-a-json-17168.patch
passerelle/apps/jsondatastore/models.py | ||
---|---|---|
31 | 31 |
return uuid.uuid4().get_hex() |
32 | 32 | |
33 | 33 | |
34 |
def clean_json_data(data): |
|
35 |
try: |
|
36 |
return json.loads(data) |
|
37 |
except ValueError: |
|
38 |
raise APIError('JSON data required') |
|
39 | ||
40 | ||
34 | 41 |
class JsonData(models.Model): |
35 | 42 |
datastore = models.ForeignKey('JsonDataStore', null=True) |
36 | 43 | |
... | ... | |
76 | 83 |
example_pattern='create', |
77 | 84 |
description=_('Create')) |
78 | 85 |
def create(self, request, name_id=None, **kwargs): |
86 |
content = clean_json_data(request.body) |
|
79 | 87 |
attrs = { |
80 |
'content': json.loads(request.body),
|
|
88 |
'content': content,
|
|
81 | 89 |
'datastore': self, |
82 | 90 |
} |
83 | 91 |
if name_id is not None: |
... | ... | |
106 | 114 |
def get_or_replace(self, request, uuid, name_id=None): |
107 | 115 |
data = self.get_data_object(uuid, name_id) |
108 | 116 |
if request.method == 'POST': |
109 |
data.content = json.loads(request.body) |
|
117 |
new_content = clean_json_data(request.body) |
|
118 |
data.content = new_content |
|
110 | 119 |
data.save() |
111 | 120 |
elif request.method == 'PATCH': |
112 |
data.content.update(json.loads(request.body)) |
|
121 |
new_content = clean_json_data(request.body) |
|
122 |
data.content.update(new_content) |
|
113 | 123 |
data.save() |
114 | 124 |
return {'id': data.uuid, 'text': data.text, 'content': data.content} |
115 | 125 |
tests/test_jsondatastore.py | ||
---|---|---|
35 | 35 |
assert len(resp.json['data']) == 1 |
36 | 36 |
assert resp.json['data'][0]['content'] == {'foo': 'bar'} |
37 | 37 | |
38 |
resp = app.post('/jsondatastore/foobar/data/create', params='foo=bar') |
|
39 |
assert resp.json['err'] == 1 # bad format, not a json |
|
40 | ||
38 | 41 |
resp = app.get('/jsondatastore/foobar/data/%s/' % uuid) |
39 | 42 |
assert resp.json['id'] == uuid |
40 | 43 |
assert resp.json['content'] == {'foo': 'bar'} |
... | ... | |
43 | 46 |
assert resp.json['id'] == uuid |
44 | 47 |
assert resp.json['content'] == {'foo': 'bar2'} |
45 | 48 | |
49 |
resp = app.post('/jsondatastore/foobar/data/%s/' % uuid, params='foo=bar2') |
|
50 |
assert resp.json['err'] == 1 # bad format, not a json |
|
51 | ||
46 | 52 |
resp = app.get('/jsondatastore/foobar/data/%s/' % uuid) |
47 | 53 |
assert resp.json['id'] == uuid |
48 | 54 |
assert resp.json['content'] == {'foo': 'bar2'} |
... | ... | |
51 | 57 |
assert resp.json['id'] == uuid |
52 | 58 |
assert resp.json['content'] == {'foo': 'bar2', 'foo2': 'bar2'} |
53 | 59 | |
60 |
resp = app.patch('/jsondatastore/foobar/data/%s/' % uuid, params='foo2=bar2') |
|
61 |
assert resp.json['err'] == 1 |
|
62 |
assert resp.json['err'] == 1 # bad format, not a json |
|
63 | ||
54 | 64 |
resp = app.post_json('/jsondatastore/foobar/data/%s/delete' % uuid) |
55 | 65 |
assert resp.json['err'] == 0 |
56 | 66 | |
57 |
- |