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
240 lines (201 loc) · 7.29 KB
/
Copy pathcorejson.py
File metadata and controls
240 lines (201 loc) · 7.29 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
from __future__ import unicode_literals
from collections import OrderedDict
from coreapi.codecs.base import BaseCodec
from coreapi.compat import string_types, force_bytes, urlparse
from coreapi.compat import COMPACT_SEPARATORS, VERBOSE_SEPARATORS
from coreapi.document import Document, Link, Array, Object, Error, Field
from coreapi.exceptions import ParseError
import json
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 _document_to_primative(node, base_url=None):
"""
Take a Core API document and return Python primatives
ready to be rendered into the JSON style encoding.
"""
if isinstance(node, Document):
ret = OrderedDict()
ret['_type'] = 'document'
# Only fill in items in '_meta' if required.
meta = OrderedDict()
url = _graceful_relative_url(base_url, node.url)
if url:
meta['url'] = url
if node.title:
meta['title'] = node.title
if meta:
ret['_meta'] = meta
ret.update([
(_escape_key(key), _document_to_primative(value, base_url=node.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.inplace is not None:
ret['inplace'] = node.inplace
if node.fields:
# Use short format for optional fields, long format for required.
ret['fields'] = [
item.name
if not item.required else
OrderedDict([('name', item.name), ('required', item.required)])
for item in node.fields
]
return ret
elif isinstance(node, Object):
return OrderedDict([
(_escape_key(key), _document_to_primative(value, base_url=base_url))
for key, value in node.items()
])
elif isinstance(node, Array):
return [_document_to_primative(value) for value in node]
elif isinstance(node, Error):
ret = OrderedDict()
ret['_type'] = 'error'
ret['messages'] = node.messages
return ret
return node
def _primative_to_document(data, base_url=None):
"""
Take Python primatives as returned from parsing JSON content,
and return a Core API document.
"""
if isinstance(data, dict) and data.get('_type') == 'document':
# Document
meta = data.get('_meta', {})
if not isinstance(meta, dict):
meta = {}
url = meta.get('url', '')
if not isinstance(url, string_types):
url = ''
url = urlparse.urljoin(base_url, url)
title = meta.get('title', '')
if not isinstance(title, string_types):
title = ''
return Document(url=url, title=title, content={
_unescape_key(key): _primative_to_document(value, url)
for key, value in data.items()
if key not in ('_type', '_meta')
})
elif isinstance(data, dict) and data.get('_type') == 'link':
# Link
url = data.get('url', '')
if not isinstance(url, string_types):
url = ''
url = urlparse.urljoin(base_url, url)
action = data.get('action')
if not isinstance(action, string_types):
action = ''
inplace = data.get('inplace')
if not isinstance(inplace, bool):
inplace = None
fields = data.get('fields', [])
if not isinstance(fields, list):
fields = []
else:
# Ignore any field items that don't match the required structure.
fields = [
item for item in fields
if isinstance(item, string_types) or (
isinstance(item, dict) and
isinstance(item.get('name'), string_types)
)
]
# Transform the strings or dicts into strings or Field instances.
fields = [
item if isinstance(item, string_types) else
Field(item['name'], required=bool(item.get('required', False)))
for item in fields
]
return Link(url=url, action=action, inplace=inplace, fields=fields)
elif isinstance(data, dict) and data.get('_type') == 'error':
# Error
messages = data.get('messages', [])
if not isinstance(messages, list):
messages = []
# Ignore any messages which are have incorrect type.
messages = [
message for message in messages
if isinstance(message, string_types)
]
return Error(messages)
elif isinstance(data, dict):
# Map
return Object({
_unescape_key(key): _primative_to_document(value, base_url)
for key, value in data.items()
if key not in ('_type', '_meta')
})
elif isinstance(data, list):
# Array
return Array([
_primative_to_document(item, base_url) for item in data
])
# String, Integer, Number, Boolean, null.
return data
class CoreJSONCodec(BaseCodec):
media_type = 'application/vnd.coreapi+json'
def load(self, bytes, base_url=None):
"""
Takes a bytestring and returns a document.
"""
try:
data = json.loads(bytes.decode('utf-8'))
except ValueError as exc:
raise ParseError('Malformed JSON. %s' % exc)
doc = _primative_to_document(data, base_url)
if not isinstance(doc, (Document, Error)):
raise ParseError('Top level node must be a document or error message.')
return doc
def dump(self, document, indent=False, **kwargs):
"""
Takes a document and returns a bytestring.
"""
if indent:
options = {
'ensure_ascii': False,
'indent': 4,
'separators': VERBOSE_SEPARATORS
}
else:
options = {
'ensure_ascii': False,
'indent': None,
'separators': COMPACT_SEPARATORS
}
data = _document_to_primative(document)
return force_bytes(json.dumps(data, **options))