|
5 | 5 | from coreapi.compat import COMPACT_SEPARATORS, VERBOSE_SEPARATORS
|
6 | 6 | from coreapi.document import Document, Link, Array, Object, Error, Field
|
7 | 7 | from coreapi.exceptions import ParseError
|
| 8 | +import coreschema |
8 | 9 | import json
|
9 | 10 |
|
10 | 11 |
|
| 12 | +# Schema encoding and decoding. |
| 13 | +# Just a naive first-pass at this point. |
| 14 | + |
| 15 | +SCHEMA_CLASS_TO_TYPE_ID = { |
| 16 | + coreschema.Object: 'object', |
| 17 | + coreschema.Array: 'array', |
| 18 | + coreschema.Number: 'number', |
| 19 | + coreschema.Integer: 'integer', |
| 20 | + coreschema.String: 'string', |
| 21 | + coreschema.Boolean: 'boolean', |
| 22 | + coreschema.Null: 'null', |
| 23 | + coreschema.Enum: 'enum', |
| 24 | + coreschema.Anything: 'anything' |
| 25 | +} |
| 26 | + |
| 27 | +TYPE_ID_TO_SCHEMA_CLASS = { |
| 28 | + value: key |
| 29 | + for key, value |
| 30 | + in SCHEMA_CLASS_TO_TYPE_ID.items() |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +def encode_schema_to_corejson(schema): |
| 35 | + type_id = SCHEMA_CLASS_TO_TYPE_ID.get(schema.__class__, 'anything') |
| 36 | + return { |
| 37 | + '_type': type_id, |
| 38 | + 'title': schema.title, |
| 39 | + 'description': schema.description |
| 40 | + } |
| 41 | + |
| 42 | + |
| 43 | +def decode_schema_from_corejson(data): |
| 44 | + type_id = _get_string(data, '_type') |
| 45 | + title = _get_string(data, 'title') |
| 46 | + description = _get_string(data, 'description') |
| 47 | + schema_cls = TYPE_ID_TO_SCHEMA_CLASS.get(type_id, coreschema.Anything) |
| 48 | + return schema_cls(title=title, description=description) |
| 49 | + |
| 50 | + |
11 | 51 | # Robust dictionary lookups, that always return an item of the correct
|
12 | 52 | # type, using an empty default if an incorrect type exists.
|
13 | 53 | # Useful for liberal parsing of inputs.
|
14 | 54 |
|
| 55 | +def _get_schema(item, key): |
| 56 | + schema_data = _get_dict(item, key) |
| 57 | + if schema_data: |
| 58 | + return decode_schema_from_corejson(schema_data) |
| 59 | + return None |
| 60 | + |
| 61 | + |
15 | 62 | def _get_string(item, key):
|
16 | 63 | value = item.get(key)
|
17 | 64 | if isinstance(value, string_types):
|
@@ -156,6 +203,8 @@ def _document_to_primative(node, base_url=None):
|
156 | 203 | ret['required'] = node.required
|
157 | 204 | if node.location:
|
158 | 205 | ret['location'] = node.location
|
| 206 | + if node.schema: |
| 207 | + ret['schema'] = encode_schema_to_corejson(node.schema) |
159 | 208 | return ret
|
160 | 209 |
|
161 | 210 | elif isinstance(node, Object):
|
@@ -213,7 +262,7 @@ def _primative_to_document(data, base_url=None):
|
213 | 262 | name=_get_string(item, 'name'),
|
214 | 263 | required=_get_bool(item, 'required'),
|
215 | 264 | location=_get_string(item, 'location'),
|
216 |
| - schema=item.get('schema', None) |
| 265 | + schema=_get_schema(item, 'schema') |
217 | 266 | )
|
218 | 267 | for item in fields if isinstance(item, dict)
|
219 | 268 | ]
|
|
0 commit comments