This repository was archived by the owner on Mar 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathcorejson.py
More file actions
338 lines (279 loc) · 9.6 KB
/
corejson.py
File metadata and controls
338 lines (279 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
from __future__ import unicode_literals
from collections import OrderedDict
from coreapi import typesys
from coreapi.codecs.base import BaseCodec
from coreapi.compat import force_bytes, string_types, urlparse
from coreapi.compat import COMPACT_SEPARATORS, VERBOSE_SEPARATORS
from coreapi.document import Document, Link, Object, Error, Field
from coreapi.exceptions import ParseError
import json
# Schema encoding and decoding.
# Just a naive first-pass at this point.
SCHEMA_CLASS_TO_TYPE_ID = {
typesys.Object: 'object',
typesys.Array: 'array',
typesys.Number: 'number',
typesys.Integer: 'integer',
typesys.String: 'string',
typesys.Boolean: 'boolean',
typesys.Any: 'anything'
}
TYPE_ID_TO_SCHEMA_CLASS = {
value: key
for key, value
in SCHEMA_CLASS_TO_TYPE_ID.items()
}
def encode_schema_to_corejson(schema):
for cls, type_id in SCHEMA_CLASS_TO_TYPE_ID.items():
if isinstance(schema, cls):
break
else:
type_id = 'anything'
retval = {
'_type': type_id,
'title': schema.title or '',
'description': schema.description or ''
}
if getattr(schema, 'enum', None) is not None:
retval['enum'] = schema.enum
return retval
def decode_schema_from_corejson(data):
type_id = _get_string(data, '_type')
title = _get_string(data, 'title')
description = _get_string(data, 'description')
kwargs = {'title': title, 'description': description}
if type_id == 'enum':
type_id = 'string'
kwargs['enum'] = _get_list(data, 'enum')
elif 'enum' in data:
kwargs['enum'] = data['enum']
schema_cls = TYPE_ID_TO_SCHEMA_CLASS.get(type_id, typesys.Any)
return schema_cls(**kwargs)
# Robust dictionary lookups, that always return an item of the correct
# type, using an empty default if an incorrect type exists.
# Useful for liberal parsing of inputs.
def _get_schema(item, key):
schema_data = _get_dict(item, key)
if schema_data:
return decode_schema_from_corejson(schema_data)
return None
def _get_string(item, key):
value = item.get(key)
if isinstance(value, string_types):
return value
return ''
def _get_dict(item, key):
value = item.get(key)
if isinstance(value, dict):
return value
return {}
def _get_list(item, key):
value = item.get(key)
if isinstance(value, list):
return value
return []
def _get_bool(item, key):
value = item.get(key)
if isinstance(value, bool):
return value
return False
def _graceful_relative_url(base_url, url):
"""
Return a graceful link for a URL relative to a base URL.
* If they are the same, return an empty string.
* If the have the same scheme and hostname, return the path & query params.
* Otherwise return the full URL.
"""
if url == base_url:
return ''
base_prefix = '%s://%s' % urlparse.urlparse(base_url or '')[0:2]
url_prefix = '%s://%s' % urlparse.urlparse(url or '')[0:2]
if base_prefix == url_prefix and url_prefix != '://':
return url[len(url_prefix):]
return url
def _escape_key(string):
"""
The '_type' and '_meta' keys are reserved.
Prefix with an additional '_' if they occur.
"""
if string.startswith('_') and string.lstrip('_') in ('type', 'meta'):
return '_' + string
return string
def _unescape_key(string):
"""
Unescape '__type' and '__meta' keys if they occur.
"""
if string.startswith('__') and string.lstrip('_') in ('type', 'meta'):
return string[1:]
return string
def _get_content(item, base_url=None):
"""
Return a dictionary of content, for documents, objects and errors.
"""
return {
_unescape_key(key): _primitive_to_document(value, base_url)
for key, value in item.items()
if key not in ('_type', '_meta')
}
def _document_to_primitive(node, base_url=None):
"""
Take a Core API document and return Python primitives
ready to be rendered into the JSON style encoding.
"""
if isinstance(node, Document):
ret = OrderedDict()
ret['_type'] = 'document'
meta = OrderedDict()
url = _graceful_relative_url(base_url, node.url)
if url:
meta['url'] = url
if node.title:
meta['title'] = node.title
if node.description:
meta['description'] = node.description
if meta:
ret['_meta'] = meta
# Fill in key-value content.
ret.update([
(_escape_key(key), _document_to_primitive(value, base_url=url))
for key, value in node.items()
])
return ret
elif isinstance(node, Error):
ret = OrderedDict()
ret['_type'] = 'error'
if node.title:
ret['_meta'] = {'title': node.title}
# Fill in key-value content.
ret.update([
(_escape_key(key), _document_to_primitive(value, base_url=base_url))
for key, value in node.items()
])
return ret
elif isinstance(node, Link):
ret = OrderedDict()
ret['_type'] = 'link'
url = _graceful_relative_url(base_url, node.url)
if url:
ret['url'] = url
if node.action:
ret['action'] = node.action
if node.encoding:
ret['encoding'] = node.encoding
if node.title:
ret['title'] = node.title
if node.description:
ret['description'] = node.description
if node.fields:
ret['fields'] = [
_document_to_primitive(field) for field in node.fields
]
return ret
elif isinstance(node, Field):
ret = OrderedDict({'name': node.name})
if node.required:
ret['required'] = node.required
if node.location:
ret['location'] = node.location
if node.schema:
ret['schema'] = encode_schema_to_corejson(node.schema)
return ret
elif isinstance(node, Object):
return OrderedDict([
(_escape_key(key), _document_to_primitive(value, base_url=base_url))
for key, value in node.items()
])
return node
def _primitive_to_document(data, base_url=None):
"""
Take Python primitives as returned from parsing JSON content,
and return a Core API document.
"""
if isinstance(data, dict) and data.get('_type') == 'document':
# Document
meta = _get_dict(data, '_meta')
url = _get_string(meta, 'url')
url = urlparse.urljoin(base_url, url)
title = _get_string(meta, 'title')
description = _get_string(meta, 'description')
content = _get_content(data, base_url=url)
return Document(
url=url,
title=title,
description=description,
media_type='application/coreapi+json',
content=content
)
if isinstance(data, dict) and data.get('_type') == 'error':
# Error
meta = _get_dict(data, '_meta')
title = _get_string(meta, 'title')
content = _get_content(data, base_url=base_url)
return Error(title=title, content=content)
elif isinstance(data, dict) and data.get('_type') == 'link':
# Link
url = _get_string(data, 'url')
url = urlparse.urljoin(base_url, url)
action = _get_string(data, 'action')
encoding = _get_string(data, 'encoding')
title = _get_string(data, 'title')
description = _get_string(data, 'description')
fields = _get_list(data, 'fields')
fields = [
Field(
name=_get_string(item, 'name'),
required=_get_bool(item, 'required'),
location=_get_string(item, 'location'),
schema=_get_schema(item, 'schema')
)
for item in fields if isinstance(item, dict)
]
return Link(
url=url, method=action, encoding=encoding,
title=title, description=description, fields=fields
)
elif isinstance(data, dict):
# Map
content = _get_content(data, base_url=base_url)
return Object(content)
# String, Integer, Number, Boolean, null.
return data
class CoreJSONCodec(BaseCodec):
media_type = 'application/coreapi+json'
format = 'corejson'
# The following is due to be deprecated...
media_types = ['application/coreapi+json', 'application/vnd.coreapi+json']
def decode(self, bytestring, **options):
"""
Takes a bytestring and returns a document.
"""
base_url = options.get('base_url')
try:
data = json.loads(bytestring.decode('utf-8'))
except ValueError as exc:
raise ParseError('Malformed JSON. %s' % exc)
doc = _primitive_to_document(data, base_url)
if isinstance(doc, Object):
doc = Document(content=dict(doc))
elif not (isinstance(doc, Document) or isinstance(doc, Error)):
raise ParseError('Top level node should be a document or error.')
return doc
def encode(self, document, **options):
"""
Takes a document and returns a bytestring.
"""
indent = options.get('indent')
if indent:
kwargs = {
'ensure_ascii': False,
'indent': 4,
'separators': VERBOSE_SEPARATORS
}
else:
kwargs = {
'ensure_ascii': False,
'indent': None,
'separators': COMPACT_SEPARATORS
}
data = _document_to_primitive(document)
return force_bytes(json.dumps(data, **kwargs))