def get_schema_fields(self, view): default = getattr(view, "ordering_name", getattr(view, "ordering")) description = ( f"{force_text(self.ordering_description)}\nAdd <b>-</b> for descending " f"ordering.\n<b><i>Default:</b></i> {default} ") ordering_fields = list( chain.from_iterable((name, f"-{name}") for name, _ in self.get_valid_fields( queryset=getattr(view, "queryset", None), view=view, context={"request": view.request}, ))) # noinspection PyArgumentList return [ coreapi.Field( name=self.ordering_param, required=False, location="query", schema=coreschema.Enum( title=force_text(self.ordering_title), description=description, enum=ordering_fields, default=default, ), ) ]
def get_schema_fields(self, view): super().get_schema_fields(view) choices = { STATES.DRAFT: 'Incomplete metadata', STATES.SUBMITTED: 'Pending validation', STATES.REFUSED: 'Refused', STATES.ACCEPTED: 'Validated', } return [ coreapi.Field( name='status', required=False, location='query', schema=coreschema.Boolean( title="Campaign status", description="0 for closed campaign, 1 for ongoing campaign" ), ), coreapi.Field( name='picture_status', required=False, location='query', schema=coreschema.Enum( choices, description=str(pformat(choices)), title="Picture status", ) ) ]
def get_schema_fields(self, view): from rest_framework.compat import coreapi, coreschema from django.utils.encoding import force_str assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' schema = coreschema.String( title=force_str(self.ordering_title), description=force_str(self.ordering_description), ) ordering_fields = getattr(view, 'ordering_fields', None) if ordering_fields and ordering_fields != '__all__': negative_fields = [ f'-{field}' for field in ordering_fields if not field.startswith('-') ] schema = coreschema.Enum( title=force_str(self.ordering_title), description=force_str(self.ordering_description), enum=sorted({*ordering_fields, *negative_fields})) return [ coreapi.Field(name=self.ordering_param, required=False, location='query', schema=schema) ]
def get_coreschema_field(self, field): description = six.text_type(field.extra.get('help_text', '')) if isinstance(field, filters.NumberFilter): return coreschema.Number(description=description) elif isinstance(field, filters.MultipleChoiceFilter): return coreschema.Array( items=coreschema.Enum(enum=[c[0] for c in field.field.choices]), description=description, unique_items=True, ) elif isinstance(field, filters.ChoiceFilter): return coreschema.Enum(enum=[c[0] for c in field.field.choices], description=description) else: return coreschema.String(description=description)
def field_to_schema(self, field): import coreschema import django.forms as django_forms from django.utils.encoding import force_str title = force_str(field.label) if field.label else '' description = force_str(field.help_text) if field.help_text else '' schema = None if isinstance(field, django_forms.MultipleChoiceField): schema = coreschema.Array( items=coreschema.Enum(enum=list(field.choices)), title=title, description=description) elif isinstance(field, django_forms.ChoiceField) and not isinstance( field, django_forms.ModelChoiceField): choices = list( map( lambda choice: choice[0] if isinstance(choice, tuple) else choice, field.choices)) choices.remove('') schema = coreschema.Enum(enum=choices, title=title, description=description) elif isinstance(field, django_forms.BooleanField): schema = coreschema.Boolean(title=title, description=description) elif isinstance(field, (django_forms.DecimalField, django_forms.FloatField)): schema = coreschema.Number(title=title, description=description) elif isinstance(field, django_forms.IntegerField): schema = coreschema.Integer(title=title, description=description) elif isinstance(field, django_forms.DateField): schema = coreschema.String(title=title, description=description, format='date') elif isinstance(field, django_forms.DateTimeField): schema = coreschema.String(title=title, description=description, format='date-time') elif isinstance(field, django_forms.JSONField): schema = coreschema.Object(title=title, description=description) return schema or coreschema.String(title=title, description=description)
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema: if issubclass(annotated_type, (bool, typesystem.Boolean)): return coreschema.Boolean() elif issubclass(annotated_type, int): return coreschema.Integer() elif issubclass(annotated_type, float): return coreschema.Number() elif issubclass(annotated_type, typesystem.Enum): enum = typing.cast(typing.Type[typesystem.Enum], annotated_type) return coreschema.Enum(enum=enum.enum) return coreschema.String()
def _annotated_type_to_coreschema( annotated_type: type) -> coreschema.schemas.Schema: if annotated_type is bool or issubclass(annotated_type, schema.Boolean): return coreschema.Boolean() elif annotated_type is int or issubclass(annotated_type, schema.Integer): return coreschema.Integer() elif annotated_type is float or issubclass(annotated_type, schema.Number): return coreschema.Number() elif issubclass(annotated_type, schema.Enum): enum = cast(Type[schema.Enum], annotated_type) return coreschema.Enum(enum=enum.enum) return coreschema.String()
def get_param_schema(annotated_type: typing.Type) -> coreschema.schemas.Schema: schema_kwargs = {'description': getattr(annotated_type, 'description', '')} if issubclass(annotated_type, (bool, typesystem.Boolean)): return coreschema.Boolean(**schema_kwargs) elif issubclass(annotated_type, int): return coreschema.Integer(**schema_kwargs) elif issubclass(annotated_type, float): return coreschema.Number(**schema_kwargs) elif issubclass(annotated_type, typesystem.Enum): enum = typing.cast(typing.Type[typesystem.Enum], annotated_type) return coreschema.Enum(enum=enum.enum, **schema_kwargs) return coreschema.String(**schema_kwargs)
def get_link(self, path, method, base_url): link = super().get_link(path, method, base_url) fields = [ Field('time_type', location='query', required=True, schema=coreschema.Enum(enum=['year', 'month'])), Field('time_value', location='query', required=True, schema=coreschema.String()), ] fields = tuple(fields) link = Link(url=link.url, action=link.action, encoding=link.encoding, fields=fields, description=link.description) document.Link() return link
def load_jsonschema(data): schemas = get_typed_schemas(data) if len(schemas) > 1: schemas = [coreschema.Union(schemas)] schemas += get_composite_schemas(data) if not schemas: schema = coreschema.Anything() elif len(schemas) == 1: schema = schemas[0] else: schema = coreschema.Intersection(schemas) if "enum" in data: # Restrict enum values by any existing type constraints, # and then use an Enum type. enum_values = [ value for value in data["enum"] if schema.validate(value) == [] ] return coreschema.Enum(enum_values) return schema
def get_schema_fields(self, view): super().get_schema_fields(view) return [ coreapi.Field( name="state", required=False, location="query", schema=coreschema.Boolean( title="Campaign state", description="'draft', 'started' or 'closed'", ), ), coreapi.Field( name="picture__state", required=False, location="query", schema=coreschema.Enum( Picture.STATES, description=str(pformat(Picture.STATES)), title="Picture state", ), ), ]
def get_schema_fields(self, view): fields = [ coreapi.Field(name=self.category_query_param, required=False, location='query', schema=coreschema.Integer( title='Category', description=force_str( self.category_query_description))), coreapi.Field(name=self.sub_category_query_param, required=False, location='query', schema=coreschema.Integer( title='Sub Category', description=force_str( self.sub_category_query_description))), coreapi.Field(name=self.author_query_param, required=False, location='query', schema=coreschema.Integer( title='Author', description=force_str( self.author_query_description))), coreapi.Field(name=self.title_query_param, required=False, location='query', schema=coreschema.String( title='Title', description=force_str( self.title_query_description))), coreapi.Field(name=self.content_query_param, required=False, location='query', schema=coreschema.String( title='Title', description=force_str( self.category_query_description))), coreapi.Field(name=self.audio_query_param, required=False, location='query', schema=coreschema.Boolean( title='Has Audio', description=force_str( self.audio_query_description))), coreapi.Field(name=self.from_year_query_param, required=False, location='query', schema=coreschema.Integer( title='From Year', description=force_str( self.from_year_query_description))), coreapi.Field(name=self.to_year_query_param, required=False, location='query', schema=coreschema.Integer( title='To Year', description=force_str( self.to_year_query_description))), coreapi.Field(name=self.sort_query_param, required=False, location='query', schema=coreschema.Enum( title='Sort by', description=force_str( self.sort_query_description), enum=[ 'publish_date', 'add_date', 'author', 'has_audio', 'pages', 'downloads', 'reads', 'rate', '-publish_date', '-add_date', '-author', '-has_audio', '-pages', '-downloads', '-reads', '-rate', ])), ] return fields
DATATYPE_TEMPERATURE: serializers.TemperaturePartialSerializer, DATATYPE_PRESSURE: serializers.PressurePartialSerializer, DATATYPE_HUMIDITY: serializers.HumidityPartialSerializer } weather_schema = ManualSchema(fields=[ coreapi.Field( "data_type", required=True, location="path", schema=coreschema.Enum( ["summary", "temperature", "pressure", "humidity"], title="Data Type", description=( "The type of response to render. One of ['summary'," "'temperature','pressure','humidity']" ) ) ), coreapi.Field( "location", required=True, location="path", schema=coreschema.String( title="Location", description=( "The location the weather forecast is requested for, " "i.e. 'Berlin,DE'" )
location='query', required=False, schema=coreschema.Number()) ]), 'set_category': Link(url='/todo/{ident}/category', action='PUT', fields=[ Field(name='ident', location='path', required=True, schema=coreschema.Integer()), Field(name='category', location='query', required=False, schema=coreschema.Enum(enum=['shop', 'chore'])) ]) }) def test_serve_schema(): response = client.get('/schema/') codec = CoreJSONCodec() document = codec.decode(response.content) assert document.url == '/schema/' for name, link in expected.links.items(): assert name in document assert link.action == document[name].action assert link.fields == document[name].fields
'oneOf': coreschema.Ref('SchemaArray'), 'not': coreschema.Ref('Schema') }, # dependancies=..., TODO default={}, ), 'SchemaArray': coreschema.Array( items=coreschema.Ref('Schema'), min_items=1, ), 'SchemaMap': coreschema.Object( additional_properties=coreschema.Ref('Schema'), default={}, ), 'SimpleTypes': coreschema.Enum( enum=['array', 'boolean', 'integer', 'null', 'number', 'object', 'string'] ), 'StringArray': coreschema.Array( items=coreschema.String(), min_items=1, unique_items=True, ) }, root='Schema') KEYWORD_TO_TYPE = { 'minimum': 'number', 'maximum': 'number', 'exclusiveMinimum': 'number', 'exclusiveMaximum': 'number', 'multipleOf': 'number',
"oneOf": coreschema.Ref("SchemaArray"), "not": coreschema.Ref("Schema"), }, # dependancies=..., TODO default={}, ), "SchemaArray": coreschema.Array(items=coreschema.Ref("Schema"), min_items=1), "SchemaMap": coreschema.Object(additional_properties=coreschema.Ref("Schema"), default={}), "SimpleTypes": coreschema.Enum(enum=[ "array", "boolean", "integer", "null", "number", "object", "string" ]), "StringArray": coreschema.Array( items=coreschema.String(), min_items=1, unique_items=True), }, root="Schema", ) KEYWORD_TO_TYPE = { "minimum": "number", "maximum": "number", "exclusiveMinimum": "number", "exclusiveMaximum": "number", "multipleOf": "number", #
'list_todo': Link( url='/todo/', action='GET', description='list_todo description', fields=[Field(name='search', location='query', required=False, schema=coreschema.String())] ), 'add_todo': Link( url='/todo/', action='POST', description='add_todo description\nMultiple indented lines', fields=[ Field(name='id', required=False, location='form', schema=coreschema.Integer()), Field(name='text', required=False, location='form', schema=coreschema.String()), Field(name='complete', required=False, location='form', schema=coreschema.Boolean()), Field(name='percent_complete', required=False, location='form', schema=coreschema.Number()), Field(name='category', required=False, location='form', schema=coreschema.Enum(enum=['shop', 'chore'])) ] ), 'show_todo': Link( url='/todo/{ident}/', action='GET', fields=[Field(name='ident', location='path', required=True, schema=coreschema.Integer())] ), 'set_complete': Link( url='/todo/{ident}/', action='PUT', fields=[ Field(name='ident', location='path', required=True, schema=coreschema.Integer()), Field(name='complete', location='query', required=False, schema=coreschema.Boolean()) ] ),
def __init__(self): manual_fields = [ coreapi.Field( "user", required=True, location="body", description="Participant information", schema=coreschema.Ref(UserSchema()), ), coreapi.Field( "position", required=True, location="body", description="Geo Position information", schema=coreschema.Ref(PositionSchema()), example="{'longitude'': '2.7105760574340807'," "'latitude': '123.3' }", ), coreapi.Field( "type", required=True, location="formData", description="Type of this participant. AF - Affected, " "HL - Helper", schema=coreschema.Enum(enum=["HL", "AF", "AU", "TP"], default="AF"), ), coreapi.Field( "firstLineOfAddress", required=True, location="formData", description="First line of address", schema=coreschema.String(default="Goerzalle 135"), ), coreapi.Field( "secondLineOfAddress", required=True, location="formData", description="Second line of address", schema=coreschema.String(default=""), ), coreapi.Field( "postCode", required=True, location="formData", description="Postcode of the location", schema=coreschema.String(default="12207"), ), coreapi.Field( "city", required=True, location="formData", description="City Name", schema=coreschema.String(default="Berlin"), ), coreapi.Field( "country", required=True, location="formData", description="Country Code", schema=coreschema.String(default="DE"), ), coreapi.Field( "placeId", required=True, location="formData", description="Place Id from Maps App", schema=coreschema.String( default="ChIJwyyKo7J3X0YRZ5XOMcLx3xo"), ), coreapi.Field( "crisis", required=True, location="formData", description="Crisis ID we are dealing with", schema=coreschema.Number(default=1), ), coreapi.Field( "phone", required=False, location="formData", description="Phone number of the participant", schema=coreschema.String(default="+4677777777"), ), ] super().__init__(fields=manual_fields, encoding="application/json")