Skip to content
This repository was archived by the owner on Mar 18, 2019. It is now read-only.

Version 3 #156

Open
wants to merge 61 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
9bc4fbb
Drop 'transform', and remove 'inplace' transformations.
tomchristie Jan 29, 2018
30e4cb1
Merge branch 'master' into remove-transform
tomchristie Jan 30, 2018
b9f9dd7
Drop action= and encoding= parameters on client, in favor of override
tomchristie Jan 30, 2018
4fb5e88
Drop HTTPTransport 'credentials' in favor of 'auth'
tomchristie Jan 30, 2018
b0eb95c
Drop HTTP request_callback and response_callback in favor of custom s…
tomchristie Jan 30, 2018
ad00b0a
Drop unused import
tomchristie Jan 30, 2018
15dcdc9
Removing data from documents. Drop 'Array'.
tomchristie Jan 30, 2018
f3c8dde
Drop CallbackAdapater. We don't use it anywhere. Could later farm it …
tomchristie Jan 31, 2018
7d06d93
Drop DomainCredentials, now that we have proper auth classes
tomchristie Jan 31, 2018
ced53cf
Refactor to use session.request
tomchristie Jan 31, 2018
93946cd
Drop unneccessary default parameters
tomchristie Jan 31, 2018
e99f71b
Move _guess_extension out of utils and into codes/download
tomchristie Jan 31, 2018
61d4198
Drop 'Document.clone'
tomchristie Feb 13, 2018
bc6aa9e
Add typesys. Add OpenAPI, JSONSchema.
tomchristie Feb 14, 2018
df86966
.errors always a classmethod
tomchristie Feb 14, 2018
f106bd0
Create absolute URLs for Links from OpenAPI
tomchristie Feb 14, 2018
6b3296a
Drop coreschema
tomchristie Feb 14, 2018
8644689
Ordered schema representations. Support OpenAPI encoding.
tomchristie Feb 14, 2018
325d032
Include yaml in requirements
tomchristie Feb 14, 2018
5984a33
Drop coreschema
tomchristie Feb 14, 2018
9444bc0
Preserve ordering of OpenAPI 'paths' across python versions
tomchristie Feb 14, 2018
b3fa5c2
Default to JSON-flavoured OpenAPI
tomchristie Feb 15, 2018
235f50e
Schemas in tests should be bytestrings
tomchristie Feb 15, 2018
dc4edea
Ensure OpenAPI.encode returns bytestrings
tomchristie Feb 15, 2018
c85818c
dict is ordered in Python 3.6
tomchristie Feb 15, 2018
566abbe
Force ordering of document using in test case
tomchristie Feb 15, 2018
6530dc2
Enforced ordering in Object
tomchristie Feb 20, 2018
09518cd
Drop commented-out YAML code
tomchristie Feb 20, 2018
73c5015
Drop itypes from transports/codecs/client
tomchristie Feb 20, 2018
2d6e0bc
Drop BaseCodec dump/load/supports
tomchristie Feb 20, 2018
48784f4
Add document.version
tomchristie Feb 20, 2018
5e19106
Drop itypes from Error
tomchristie Feb 20, 2018
d1c006f
Drop itypes from Link
tomchristie Feb 20, 2018
b52553e
Drop itypes
tomchristie Feb 20, 2018
b1e3418
Drop client.reload
tomchristie Feb 20, 2018
7b0cf7d
_to_immutable -> _to_objects
tomchristie Feb 20, 2018
e663b9f
Drop reload from tests
tomchristie Feb 20, 2018
f09ca74
'enum' defined on types
tomchristie Feb 20, 2018
93482e9
Add openapi codec to setup
tomchristie Feb 20, 2018
54199e3
Add Field.title
tomchristie Feb 20, 2018
8c1748e
Use Link.method. Put .action towards deprecation.
tomchristie Feb 20, 2018
ae79ef5
Plain old classes for typesys
tomchristie Feb 21, 2018
01a0a51
Add typesys.Ref
tomchristie Feb 21, 2018
46a9559
assert types on __init__
tomchristie Feb 21, 2018
f772992
Tests and refinements to typesys
tomchristie Feb 21, 2018
a50e0e3
exact_items validation for Array
tomchristie Feb 21, 2018
b56b1d6
Add allow_null to typesys
tomchristie Feb 21, 2018
c58ad81
Work on JSON Schema and typesys
tomchristie Mar 1, 2018
15f24dc
Work on Union and JSONSchema
tomchristie Mar 1, 2018
cb8e273
Cleanups on typesys
tomchristie Mar 1, 2018
f19c680
Uniqueness checking always that always uses set()
tomchristie Mar 5, 2018
a87f66a
Add Section, Add Link.id
tomchristie Mar 5, 2018
382eef8
Slugify tag names to get section ids
tomchristie Mar 5, 2018
4a5993a
Add path_links and query_links to Section
tomchristie Mar 6, 2018
5e3de6c
Add path_fields and query_fields to Link
tomchristie Mar 6, 2018
1d7a121
Tweak
tomchristie Mar 6, 2018
58ec296
Fix 'security' in OpenAPI
tomchristie Mar 6, 2018
947e03b
If no operationId then use summary for Link.id
tomchristie Mar 6, 2018
7486932
Building out OpenAPI v3 spec
tomchristie Mar 6, 2018
69a5a69
First pass at parsing OpenAPI requestBody schemas
tomchristie Mar 6, 2018
3a793b9
Add initial requestBody schema support
tomchristie Mar 6, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add typesys. Add OpenAPI, JSONSchema.
  • Loading branch information
tomchristie committed Feb 14, 2018
commit bc6aa9eb4f59ce6f393730a4970200eb0f291270
6 changes: 3 additions & 3 deletions coreapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# coding: utf-8
from coreapi import auth, codecs, exceptions, transports, utils
from coreapi import auth, codecs, exceptions, transports, typesys, utils
from coreapi.client import Client
from coreapi.document import Document, Link, Object, Error, Field


__version__ = '2.3.3'
__version__ = '3.0.0'
__all__ = [
'Document', 'Link', 'Object', 'Error', 'Field',
'Client',
'auth', 'codecs', 'exceptions', 'transports', 'utils',
'auth', 'codecs', 'exceptions', 'transports', 'typesys', 'utils',
]
7 changes: 5 additions & 2 deletions coreapi/codecs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
from coreapi.codecs.display import DisplayCodec
from coreapi.codecs.download import DownloadCodec
from coreapi.codecs.jsondata import JSONCodec
from coreapi.codecs.jsonschema import JSONSchemaCodec
from coreapi.codecs.openapi import OpenAPICodec
from coreapi.codecs.python import PythonCodec
from coreapi.codecs.text import TextCodec


__all__ = [
'BaseCodec', 'CoreJSONCodec', 'DisplayCodec',
'JSONCodec', 'PythonCodec', 'TextCodec', 'DownloadCodec'
'BaseCodec', 'CoreJSONCodec', 'DisplayCodec', 'JSONCodec',
'JSONSchemaCodec', 'OpenAPICodec', 'PythonCodec', 'TextCodec',
'DownloadCodec'
]
166 changes: 166 additions & 0 deletions coreapi/codecs/jsonschema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
from coreapi import typesys
from coreapi.codecs.base import BaseCodec
from coreapi.compat import COMPACT_SEPARATORS, VERBOSE_SEPARATORS, force_bytes
from coreapi.exceptions import ParseError
from coreapi.schemas import JSONSchema
import collections
import json


class JSONSchemaCodec(BaseCodec):
media_type = 'application/schema+json'

def decode(self, bytestring, **options):
try:
data = json.loads(
bytestring.decode('utf-8'),
object_pairs_hook=collections.OrderedDict
)
except ValueError as exc:
raise ParseError('Malformed JSON. %s' % exc)
jsonschema = JSONSchema(data)
return self.decode_from_data_structure(jsonschema)

def decode_from_data_structure(self, struct):
attrs = {}

if '$ref' in struct:
if struct['$ref'] == '#':
return typesys.ref()
name = struct['$ref'].split('/')[-1]
return typesys.ref(name)

if struct['type'] == 'string':
if 'minLength' in struct:
attrs['min_length'] = struct['minLength']
if 'maxLength' in struct:
attrs['max_length'] = struct['maxLength']
if 'pattern' in struct:
attrs['pattern'] = struct['pattern']
if 'format' in struct:
attrs['format'] = struct['format']
return typesys.string(**attrs)

if struct['type'] in ['number', 'integer']:
if 'minimum' in struct:
attrs['minimum'] = struct['minimum']
if 'maximum' in struct:
attrs['maximum'] = struct['maximum']
if 'exclusiveMinimum' in struct:
attrs['exclusiveMinimum'] = struct['exclusiveMinimum']
if 'exclusiveMaximum' in struct:
attrs['exclusiveMaximum'] = struct['exclusiveMaximum']
if 'multipleOf' in struct:
attrs['multipleOf'] = struct['multipleOf']
if struct['type'] == 'integer':
return typesys.integer(**attrs)
return typesys.number(**attrs)

if struct['type'] == 'boolean':
return typesys.boolean()

if struct['type'] == 'object':
if 'properties' in struct:
attrs['properties'] = {
key: self.decode_from_data_structure(value)
for key, value in struct['properties'].items()
}
if 'required' in struct:
attrs['required'] = struct['required']
return typesys.obj(**attrs)

if struct['type'] == 'array':
if 'items' in struct:
attrs['items'] = self.decode_from_data_structure(struct['items'])
if 'additionalItems' in struct:
attrs['additional_items'] = struct['additionalItems']
if 'minItems' in struct:
attrs['min_items'] = struct['minItems']
if 'maxItems' in struct:
attrs['max_items'] = struct['maxItems']
if 'uniqueItems' in struct:
attrs['unique_items'] = struct['uniqueItems']
return typesys.array(**attrs)

def encode(self, cls, **options):
struct = self.encode_to_data_structure(cls)
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
}
return force_bytes(json.dumps(struct, **kwargs))

def encode_to_data_structure(self, cls):
if issubclass(cls, typesys.String):
value = {'type': 'string'}
if cls.max_length is not None:
value['maxLength'] = cls.max_length
if cls.min_length is not None:
value['minLength'] = cls.min_length
if cls.pattern is not None:
value['pattern'] = cls.pattern
if cls.format is not None:
value['format'] = cls.format
return value

if issubclass(cls, typesys.NumericType):
if issubclass(cls, typesys.Integer):
value = {'type': 'integer'}
else:
value = {'type': 'number'}

if cls.minimum is not None:
value['minimum'] = cls.minimum
if cls.maximum is not None:
value['maximum'] = cls.maximum
if cls.exclusive_minimum:
value['exclusiveMinimum'] = cls.exclusive_minimum
if cls.exclusive_maximum:
value['exclusiveMaximum'] = cls.exclusive_maximum
if cls.multiple_of is not None:
value['multipleOf'] = cls.multiple_of
return value

if issubclass(cls, typesys.Boolean):
return {'type': 'boolean'}

if issubclass(cls, typesys.Object):
value = {'type': 'object'}
if cls.properties:
value['properties'] = {
key: self.encode_to_data_structure(value)
for key, value in cls.properties.items()
}
if cls.required:
value['required'] = cls.required
return value

if issubclass(cls, typesys.Array):
value = {'type': 'array'}
if cls.items is not None:
value['items'] = self.encode_to_data_structure(cls.items)
if cls.additional_items:
value['additionalItems'] = cls.additional_items
if cls.min_items is not None:
value['minItems'] = cls.min_items
if cls.max_items is not None:
value['maxItems'] = cls.max_items
if cls.unique_items is not None:
value['uniqueItems'] = cls.unique_items
return value

if issubclass(cls, typesys.Ref):
if not cls.to:
return {'$ref': '#'}
return {'$ref': '#/definitions/%s' % cls.to}

raise Exception('Cannot encode class %s' % cls)
94 changes: 94 additions & 0 deletions coreapi/codecs/openapi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from coreapi.codecs import BaseCodec, JSONSchemaCodec
from coreapi.document import Document, Link, Field
from coreapi.schemas import OpenAPI
import yaml


METHODS = [
'get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'
]


class OpenAPICodec(BaseCodec):
media_type = 'application/vnd.oai.openapi'
format = 'openapi'

def decode(self, bytestring, **options):
data = yaml.safe_load(bytestring)
openapi = OpenAPI(data)
title = openapi.lookup(['info', 'title'])
description = openapi.lookup(['info', 'description'])
url = openapi.lookup(['servers', 0, 'url'])
content = self.get_links(openapi)
return Document(title=title, description=description, url=url, content=content)

def get_links(self, openapi):
"""
Return all the links in the document, layed out by tag and operationId.
"""
content = {}

for path, path_info in openapi.get('paths', {}).items():
operations = {
key: path_info[key] for key in path_info
if key in METHODS
}
for operation, operation_info in operations.items():
operationId = operation_info.get('operationId')
tag = operation_info.lookup(['tags', 0])
if not operationId:
continue

link = self.get_link(path, path_info, operation, operation_info)
if tag is None:
content[operationId] = link
else:
if tag in content:
content[tag][operationId] = link
else:
content[tag] = {operationId: link}

return content

def get_link(self, path, path_info, operation, operation_info):
"""
Return a single link in the document.
"""
title = operation_info.get('summary')
description = operation_info.get('description')
parameters = path_info.get('parameters', [])
parameters += operation_info.get('parameters', [])

fields = [
self.get_field(parameter)
for parameter in parameters
]

return Link(
url=path,
action=operation,
title=title,
description=description,
fields=fields
)

def get_field(self, parameter):
"""
Return a single field in a link.
"""
name = parameter.get('name')
location = parameter.get('in')
description = parameter.get('description')
required = parameter.get('required', False)
schema = parameter.get('schema')

if schema is not None:
schema = JSONSchemaCodec().decode_from_data_structure(schema)

return Field(
name=name,
location=location,
description=description,
required=required,
schema=schema
)
31 changes: 22 additions & 9 deletions coreapi/document.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# coding: utf-8
from __future__ import unicode_literals
from collections import OrderedDict, namedtuple
from collections import OrderedDict
from coreapi.compat import string_types
import itypes

Expand Down Expand Up @@ -40,14 +40,6 @@ def _key_sorting(item):
return (0, key)


# The field class, as used by Link objects:

# NOTE: 'type', 'description' and 'example' are now deprecated,
# in favor of 'schema'.
Field = namedtuple('Field', ['name', 'required', 'location', 'schema', 'description', 'type', 'example'])
Field.__new__.__defaults__ = (False, '', None, None, None, None)


# The Core API primitives:

class Document(itypes.Dict):
Expand Down Expand Up @@ -238,6 +230,27 @@ def __str__(self):
return _str(self)


class Field(object):
def __init__(self, name, required=False, location='', schema=None, description=None, example=None):
self.name = name
self.required = required
self.location = location
self.schema = schema
self.description = description
self.example = example

def __eq__(self, other):
return (
isinstance(other, Field) and
self.name == other.name and
self.required == other.required and
self.location == other.location and
self.description == other.description and
self.schema.__class__ == other.schema.__class__ and
self.example == other.example
)


class Error(itypes.Dict):
def __init__(self, title=None, content=None):
data = {} if (content is None) else content
Expand Down
5 changes: 5 additions & 0 deletions coreapi/schemas/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from coreapi.schemas.jsonschema import JSONSchema
from coreapi.schemas.openapi import OpenAPI


__all__ = ['JSONSchema', 'OpenAPI']
32 changes: 32 additions & 0 deletions coreapi/schemas/jsonschema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from coreapi import typesys


class JSONSchema(typesys.Object):
properties = {
'$ref': typesys.string(),
'type': typesys.string(),

# String
'minLength': typesys.integer(minimum=0, default=0),
'maxLength': typesys.integer(minimum=0),
'pattern': typesys.string(format='regex'),
'format': typesys.string(),

# Numeric
'minimum': typesys.number(),
'maximum': typesys.number(),
'exclusiveMinimum': typesys.boolean(default=False),
'exclusiveMaximum': typesys.boolean(default=False),
'multipleOf': typesys.number(minimum=0.0, exclusive_minimum=True),

# Object
'properties': typesys.obj(), # TODO: typesys.ref('JSONSchema'),
'required': typesys.array(items=typesys.string(), min_items=1, unique=True),

# Array
'items': typesys.obj(), # TODO: typesys.ref('JSONSchema'),
'additionalItems': typesys.boolean(),
'minItems': typesys.integer(minimum=0),
'maxItems': typesys.integer(minimum=0),
'uniqueItems': typesys.boolean(),
}
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy