[Python-experimental] types now classes, adds additionalProperties handling (#4154)

* Changes python-experimental types to classes, adds additionalalproperties handling

Adds model_utils update, updates model.mustache

Updates api.mustache and uses model_to_dict in model_normal.mustache

Updates requirements.mustache for PythonClientExperimental

Passes through check_type when deserializing models

Converts types from strings to classes in PythonClientExperimentalCodegen.java and PythonTest.java

Creates PythonClientExperimentalTest.java

Updates toInstantiationType to use ModelUtils.xxx

Corrects docstring descriptions of response_type

Updates python-experimental typing, partially fixes deserialization tests

Adds fixes for some of the deserialization tests

Fixes deserialization tests

Switches model teplates to use allVars so allof props will be included

Fixes tests.test_enum_arrays

Fixes test_to_str

Adds additional_properties_type, fixes teast_todict in test_map_test.py

Correctly check the type of _request_timeout values

Fixes test_upload_file test

Turns off coercion when instantiating model types with client data

Updates file handling to input and output an open file object

Fixes linting errors

Adds fixes for python2 tests, linting fixes

Adds additionalproperties to docs + tests

Regenerates python-experimatal client

* Regenerates python-experimental client

* Updates windows python-experimental bat file

* Fixes addModelImport so client generation will work with the v2 spec

* Reverts PythonClientCodegen.java

* Acutally revert PythonClientCodegen.java

* Updates the sample example for file_type in docs

* Silences line too long error for python models so CI tests pass

* Fixes handling of file uploads, adds tests for uploading files

* Removes comment

* Fixes mock installation in python2

* Limit mock addition to python-experimental test requirements only

* Removes SmartBear copyright line
This commit is contained in:
Justin Black
2019-10-28 06:24:31 -07:00
committed by William Cheng
parent c0bc8b4934
commit 73c55c11dd
125 changed files with 12213 additions and 5498 deletions

View File

@@ -5,6 +5,6 @@ If Not Exist %executable% (
) )
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
set ags=generate -i modules\openapi-generator\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -g python-experimental -o samples\client\petstore\python-experimental -DpackageName=petstore_api set ags=generate -i modules\openapi-generator\src\test\resources\2_0\python-client-experimental\petstore-with-fake-endpoints-models-for-testing.yaml -g python-experimental -o samples\client\petstore\python-experimental --additional-properties packageName=petstore_api
java %JAVA_OPTS% -jar %executable% %ags% java %JAVA_OPTS% -jar %executable% %ags%

View File

@@ -3624,7 +3624,7 @@ public class DefaultCodegen implements CodegenConfig {
co.baseName = tag; co.baseName = tag;
} }
private void addParentContainer(CodegenModel model, String name, Schema schema) { protected void addParentContainer(CodegenModel model, String name, Schema schema) {
final CodegenProperty property = fromProperty(name, schema); final CodegenProperty property = fromProperty(name, schema);
addImport(model, property.complexType); addImport(model, property.complexType);
model.parent = toInstantiationType(schema); model.parent = toInstantiationType(schema);

View File

@@ -50,6 +50,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
public PythonClientExperimentalCodegen() { public PythonClientExperimentalCodegen() {
super(); super();
// this may set datatype right for additional properties
instantiationTypes.put("map", "dict");
apiTemplateFiles.remove("api.mustache"); apiTemplateFiles.remove("api.mustache");
apiTemplateFiles.put("python-experimental/api.mustache", ".py"); apiTemplateFiles.put("python-experimental/api.mustache", ".py");
@@ -76,6 +79,20 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
supportingFiles.add(new SupportingFile("python-experimental/model_utils.mustache", packagePath(), "model_utils.py")); supportingFiles.add(new SupportingFile("python-experimental/model_utils.mustache", packagePath(), "model_utils.py"));
Boolean generateSourceCodeOnly = false;
if (additionalProperties.containsKey(CodegenConstants.SOURCECODEONLY_GENERATION)) {
generateSourceCodeOnly = Boolean.valueOf(additionalProperties.get(CodegenConstants.SOURCECODEONLY_GENERATION).toString());
}
if (!generateSourceCodeOnly) {
supportingFiles.remove(new SupportingFile("setup.mustache", "", "setup.py"));
supportingFiles.add(new SupportingFile("python-experimental/setup.mustache", "", "setup.py"));
supportingFiles.remove(new SupportingFile("requirements.mustache", "", "requirements.txt"));
supportingFiles.add(new SupportingFile("python-experimental/requirements.mustache", "", "requirements.txt"));
supportingFiles.remove(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt"));
supportingFiles.add(new SupportingFile("python-experimental/test-requirements.mustache", "", "test-requirements.txt"));
}
// default this to true so the python ModelSimple models will be generated // default this to true so the python ModelSimple models will be generated
ModelUtils.setGenerateAliasAsModel(true); ModelUtils.setGenerateAliasAsModel(true);
LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums"); LOGGER.info(CodegenConstants.GENERATE_ALIAS_AS_MODEL + " is hard coded to true in this generator. Alias models will only be generated if they contain validations or enums");
@@ -196,10 +213,20 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
} }
} }
@Override public void addModelImport(Map<String, Object> objs, CodegenModel cm, String otherModelName) {
public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { // adds the absolute path to otherModelName as an import in CodegenModel cm
// add regex information to property HashMap referencedModel = (HashMap) objs.get(otherModelName);
postProcessPattern(property.pattern, property.vendorExtensions); if (referencedModel == null) {
// this happens with a model where type=string and format=number which is a non-standard format
return;
}
ArrayList myModel = (ArrayList) referencedModel.get("models");
HashMap modelData = (HashMap) myModel.get(0);
String importPath = (String) modelData.get("importPath");
// only add importPath to parameters if it isn't in importPaths
if (!cm.imports.contains(importPath)) {
cm.imports.add(importPath);
}
} }
// override with any special post-processing for all models // override with any special post-processing for all models
@@ -213,6 +240,41 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models"); List<Map<String, Object>> models = (List<Map<String, Object>>) inner.get("models");
for (Map<String, Object> mo : models) { for (Map<String, Object> mo : models) {
CodegenModel cm = (CodegenModel) mo.get("model"); CodegenModel cm = (CodegenModel) mo.get("model");
// fix the imports that each model has, change them to absolute
// imports
// clear out imports so we will only include full path imports
cm.imports.clear();
CodegenDiscriminator discriminator = cm.discriminator;
if (discriminator != null) {
Set<CodegenDiscriminator.MappedModel> mappedModels = discriminator.getMappedModels();
for (CodegenDiscriminator.MappedModel mappedModel : mappedModels) {
String otherModelName = mappedModel.getModelName();
addModelImport(objs, cm, otherModelName);
}
}
ArrayList<List<CodegenProperty>> listOfLists= new ArrayList<List<CodegenProperty>>();
listOfLists.add(cm.allVars);
listOfLists.add(cm.requiredVars);
listOfLists.add(cm.optionalVars);
listOfLists.add(cm.vars);
for (List<CodegenProperty> varList : listOfLists) {
for (CodegenProperty cp : varList) {
String otherModelName = null;
if (cp.complexType != null) {
otherModelName = cp.complexType;
}
if (cp.mostInnerItems != null) {
if (cp.mostInnerItems.complexType != null) {
otherModelName = cp.mostInnerItems.complexType;
}
}
if (otherModelName != null) {
addModelImport(objs, cm, otherModelName);
}
}
}
Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name); Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name);
CodegenProperty modelProperty = fromProperty("value", modelSchema); CodegenProperty modelProperty = fromProperty("value", modelSchema);
if (cm.isEnum || cm.isAlias) { if (cm.isEnum || cm.isAlias) {
@@ -491,11 +553,6 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
} }
} }
@Override
public void postProcessParameter(CodegenParameter parameter) {
postProcessPattern(parameter.pattern, parameter.vendorExtensions);
}
/** /**
* Convert OAS Model object to Codegen Model object * Convert OAS Model object to Codegen Model object
* *
@@ -559,11 +616,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
} }
} }
// return all models which don't need their properties connected to non-object models // set regex values, before it was only done on model.vars
if (propertyToModelName.isEmpty()) {
return result;
}
// fix all property references to non-object models, make those properties non-primitive and // fix all property references to non-object models, make those properties non-primitive and
// set their dataType and complexType to the model name, so documentation will refer to the correct model // set their dataType and complexType to the model name, so documentation will refer to the correct model
ArrayList<List<CodegenProperty>> listOfLists = new ArrayList<List<CodegenProperty>>(); ArrayList<List<CodegenProperty>> listOfLists = new ArrayList<List<CodegenProperty>>();
@@ -575,6 +628,9 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
listOfLists.add(result.readWriteVars); listOfLists.add(result.readWriteVars);
for (List<CodegenProperty> cpList : listOfLists) { for (List<CodegenProperty> cpList : listOfLists) {
for (CodegenProperty cp : cpList) { for (CodegenProperty cp : cpList) {
// set regex values, before it was only done on model.vars
postProcessModelProperty(result, cp);
// fix references to non-object models
if (!propertyToModelName.containsKey(cp.name)) { if (!propertyToModelName.containsKey(cp.name)) {
continue; continue;
} }
@@ -589,4 +645,147 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen {
return result; return result;
} }
/**
* Output the type declaration of the property
*
* @param schema property schema
* @return a string presentation of the property type
*/
public String getSimpleTypeDeclaration(Schema schema) {
String oasType = getSchemaType(schema);
if (typeMapping.containsKey(oasType)) {
return typeMapping.get(oasType);
}
return oasType;
}
public String getTypeString(Schema p, String prefix, String suffix) {
// this is used to set dataType, which defines a python tuple of classes
String fullSuffix = suffix;
if (")".equals(suffix)) {
fullSuffix = "," + suffix;
}
if (ModelUtils.isNullable(p)) {
fullSuffix = ", none_type" + suffix;
}
if (ModelUtils.isFreeFormObject(p) && ModelUtils.getAdditionalProperties(p) == null) {
return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix;
}
if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return prefix + "{str: " + getTypeString(inner, "(", ")") + "}" + fullSuffix;
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return prefix + "[" + getTypeString(inner, "", "") + "]" + fullSuffix;
}
String baseType = getSimpleTypeDeclaration(p);
if (ModelUtils.isFileSchema(p)) {
baseType = "file_type";
}
return prefix + baseType + fullSuffix;
}
/**
* Output the type declaration of a given name
*
* @param p property schema
* @return a string presentation of the type
*/
@Override
public String getTypeDeclaration(Schema p) {
// this is used to set dataType, which defines a python tuple of classes
// in Python we will wrap this in () to make it a tuple but here we
// will omit the parens so the generated documentaion will not include
// them
return getTypeString(p, "", "");
}
@Override
public String toInstantiationType(Schema property) {
if (ModelUtils.isArraySchema(property) || ModelUtils.isMapSchema(property) || property.getAdditionalProperties() != null) {
return getSchemaType(property);
}
return super.toInstantiationType(property);
}
@Override
protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel, Schema schema) {
Schema addProps = ModelUtils.getAdditionalProperties(schema);
if (addProps != null && addProps.get$ref() == null) {
// if AdditionalProperties exists and is an inline definition, get its datatype and store it in m.parent
String typeString = getTypeDeclaration(addProps);
codegenModel.additionalPropertiesType = typeString;
} else {
addParentContainer(codegenModel, codegenModel.name, schema);
}
}
@Override
public void setParameterExampleValue(CodegenParameter p) {
// we have a custom version of this function so we can set the file
// type example value
String example;
if (p.defaultValue == null) {
example = p.example;
} else {
p.example = p.defaultValue;
return;
}
String type = p.baseType;
if (type == null) {
type = p.dataType;
}
if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) {
if (example == null) {
example = p.paramName + "_example";
}
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type) || "int".equals(type)) {
if (example == null) {
example = "56";
}
} else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) {
if (example == null) {
example = "3.4";
}
} else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) {
if (example == null) {
example = "True";
}
} else if ("file".equalsIgnoreCase(type)) {
if (example == null) {
example = "/path/to/file";
}
example = "open('"+example+"', 'rb')";
} else if ("Date".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "'" + escapeText(example) + "'";
} else if ("DateTime".equalsIgnoreCase(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "'" + escapeText(example) + "'";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = this.packageName + "." + type + "()";
} else {
LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue");
}
if (example == null) {
example = "None";
} else if (Boolean.TRUE.equals(p.isListContainer)) {
example = "[" + example + "]";
} else if (Boolean.TRUE.equals(p.isMapContainer)) {
example = "{'key': " + example + "}";
}
p.example = example;
}
} }

View File

@@ -14,10 +14,20 @@ from {{packageName}}.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from {{packageName}}.model_utils import ( from {{packageName}}.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
{{#imports}}
{{{import}}}
{{/imports}}
{{#operations}} {{#operations}}
@@ -51,24 +61,51 @@ class {{classname}}(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
{{#allParams}} {{#allParams}}
:param {{dataType}} {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} :param {{dataType}} {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
{{/allParams}} {{/allParams}}
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
{{#requiredParams}} {{#requiredParams}}
kwargs['{{paramName}}'] = {{paramName}} kwargs['{{paramName}}'] = {{paramName}}
{{/requiredParams}} {{/requiredParams}}
@@ -76,7 +113,7 @@ class {{classname}}(object):
self.{{operationId}} = Endpoint( self.{{operationId}} = Endpoint(
settings={ settings={
'response_type': {{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, 'response_type': {{#returnType}}({{{returnType}}},){{/returnType}}{{^returnType}}None{{/returnType}},
{{#authMethods}} {{#authMethods}}
{{#-first}} {{#-first}}
'auth': [ 'auth': [
@@ -178,7 +215,7 @@ class {{classname}}(object):
}, },
'openapi_types': { 'openapi_types': {
{{#allParams}} {{#allParams}}
'{{paramName}}': '{{dataType}}', '{{paramName}}': ({{{dataType}}},),
{{/allParams}} {{/allParams}}
}, },
'attribute_map': { 'attribute_map': {
@@ -237,7 +274,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -273,11 +310,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -291,8 +341,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -303,6 +352,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -316,14 +379,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -348,20 +417,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -370,7 +434,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -409,9 +477,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -2,14 +2,10 @@
{{>partial_header}} {{>partial_header}}
from __future__ import absolute_import from __future__ import absolute_import
import datetime
import inspect
import json import json
import mimetypes import mimetypes
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
import os import os
import re
import tempfile
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
import six import six
@@ -18,14 +14,20 @@ from six.moves.urllib.parse import quote
import tornado.gen import tornado.gen
{{/tornado}} {{/tornado}}
import {{modelPackage}}
from {{packageName}} import rest from {{packageName}} import rest
from {{packageName}}.configuration import Configuration from {{packageName}}.configuration import Configuration
from {{packageName}}.exceptions import ApiValueError
from {{packageName}}.model_utils import ( from {{packageName}}.model_utils import (
ModelNormal, ModelNormal,
ModelSimple ModelSimple,
date,
datetime,
deserialize_file,
file_type,
model_to_dict,
str,
validate_and_convert_types
) )
from {{packageName}}.exceptions import ApiValueError
class ApiClient(object): class ApiClient(object):
@@ -50,17 +52,11 @@ class ApiClient(object):
to the API. More threads means more concurrent API requests. to the API. More threads means more concurrent API requests.
""" """
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types # six.binary_type python2=str, python3=bytes
NATIVE_TYPES_MAPPING = { # six.text_type python2=unicode, python3=str
'int': int, PRIMITIVE_TYPES = (
'long': int if six.PY3 else long, # noqa: F821 (float, bool, six.binary_type, six.text_type) + six.integer_types
'float': float, )
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
_pool = None _pool = None
def __init__(self, configuration=None, header_name=None, header_value=None, def __init__(self, configuration=None, header_name=None, header_value=None,
@@ -113,7 +109,8 @@ class ApiClient(object):
query_params=None, header_params=None, body=None, post_params=None, query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None, files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None, _return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None, _host=None): _preload_content=True, _request_timeout=None, _host=None,
_check_type=None):
config = self.configuration config = self.configuration
@@ -180,7 +177,11 @@ class ApiClient(object):
if _preload_content: if _preload_content:
# deserialize response data # deserialize response data
if response_type: if response_type:
return_data = self.deserialize(response_data, response_type) return_data = self.deserialize(
response_data,
response_type,
_check_type
)
else: else:
return_data = None return_data = None
@@ -223,93 +224,73 @@ class ApiClient(object):
elif isinstance(obj, tuple): elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj) return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj) for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)): elif isinstance(obj, (datetime, date)):
return obj.isoformat() return obj.isoformat()
if isinstance(obj, dict): if isinstance(obj, dict):
obj_dict = obj obj_dict = obj
elif isinstance(obj, ModelNormal): elif isinstance(obj, ModelNormal):
# Convert model obj to dict except # Convert model obj to dict
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in # Convert attribute name to json key in
# model definition for request. # model definition for request
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) obj_dict = model_to_dict(obj, serialize=True)
for attr, _ in six.iteritems(obj.openapi_types)
if getattr(obj, attr) is not None}
elif isinstance(obj, ModelSimple): elif isinstance(obj, ModelSimple):
return self.sanitize_for_serialization(obj.value) return self.sanitize_for_serialization(obj.value)
return {key: self.sanitize_for_serialization(val) return {key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)} for key, val in six.iteritems(obj_dict)}
def deserialize(self, response, response_type): def deserialize(self, response, response_type, _check_type):
"""Deserializes response into an object. """Deserializes response into an object.
:param response: RESTResponse object to be deserialized. :param response: RESTResponse object to be deserialized.
:param response_type: class literal for :param response_type: For the response, a tuple containing:
deserialized object, or string of class name. valid classes
a list containing valid classes (for list schemas)
a dict containing a tuple of valid classes as the value
Example values:
(str,)
(Pet,)
(float, none_type)
([int, none_type],)
({str: (bool, str, int, float, date, datetime, str, none_type)},)
:param _check_type: boolean, whether to check the types of the data
received from the server
:return: deserialized object. :return: deserialized object.
""" """
# handle file downloading # handle file downloading
# save response body into a tmp file and return the instance # save response body into a tmp file and return the instance
if response_type == "file": if response_type == (file_type,):
return self.__deserialize_file(response) content_disposition = response.getheader("Content-Disposition")
return deserialize_file(response.data, self.configuration,
content_disposition=content_disposition)
# fetch data from response object # fetch data from response object
try: try:
data = json.loads(response.data) received_data = json.loads(response.data)
except ValueError: except ValueError:
data = response.data received_data = response.data
return self.__deserialize(data, response_type) # store our data under the key of 'received_data' so users have some
# context if they are deserializing a string and the data type is wrong
def __deserialize(self, data, klass): deserialized_data = validate_and_convert_types(
"""Deserializes dict, list, str into an object. received_data,
response_type,
:param data: dict, list or str. ['received_data'],
:param klass: class literal, or string of class name. True,
_check_type,
:return: object. configuration=self.configuration
""" )
if data is None: return deserialized_data
return None
if type(klass) == str:
if klass.startswith('list['):
sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('dict('):
sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr({{modelPackage}}, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
def call_api(self, resource_path, method, def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None, path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None, body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None, response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None, _return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None, _host=None): _preload_content=True, _request_timeout=None, _host=None,
_check_type=None):
"""Makes the HTTP request (synchronous) and returns deserialized data. """Makes the HTTP request (synchronous) and returns deserialized data.
To make an async_req request, set the async_req parameter. To make an async_req request, set the async_req parameter.
@@ -324,9 +305,18 @@ class ApiClient(object):
:param post_params dict: Request post form parameters, :param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`. for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request. :param auth_settings list: Auth Settings names for the request.
:param response: Response data type. :param response_type: For the response, a tuple containing:
:param files dict: key -> filename, value -> filepath, valid classes
for `multipart/form-data`. a list containing valid classes (for list schemas)
a dict containing a tuple of valid classes as the value
Example values:
(str,)
(Pet,)
(float, none_type)
([int, none_type],)
({str: (bool, str, int, float, date, datetime, str, none_type)},)
:param files dict: key -> field name, value -> a list of open file
objects for `multipart/form-data`.
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code :param _return_http_data_only: response data without head status code
and headers and headers
@@ -339,6 +329,8 @@ class ApiClient(object):
number provided, it will be total request number provided, it will be total request
timeout. It can also be a pair (tuple) of timeout. It can also be a pair (tuple) of
(connection, read) timeouts. (connection, read) timeouts.
:param _check_type: boolean describing if the data back from the server
should have its type checked.
:return: :return:
If async_req parameter is True, If async_req parameter is True,
the request will be called asynchronously. the request will be called asynchronously.
@@ -352,7 +344,8 @@ class ApiClient(object):
body, post_params, files, body, post_params, files,
response_type, auth_settings, response_type, auth_settings,
_return_http_data_only, collection_formats, _return_http_data_only, collection_formats,
_preload_content, _request_timeout, _host) _preload_content, _request_timeout, _host,
_check_type)
else: else:
thread = self.pool.apply_async(self.__call_api, (resource_path, thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params, method, path_params, query_params,
@@ -363,7 +356,7 @@ class ApiClient(object):
collection_formats, collection_formats,
_preload_content, _preload_content,
_request_timeout, _request_timeout,
_host)) _host, _check_type))
return thread return thread
def request(self, method, url, query_params=None, headers=None, def request(self, method, url, query_params=None, headers=None,
@@ -460,24 +453,34 @@ class ApiClient(object):
def files_parameters(self, files=None): def files_parameters(self, files=None):
"""Builds form parameters. """Builds form parameters.
:param files: File parameters. :param files: None or a dict with key=param_name and
:return: Form parameters with files. value is a list of open file objects
:return: List of tuples of form parameters with file data
""" """
params = [] if files is None:
return []
if files: params = []
for k, v in six.iteritems(files): for param_name, file_instances in six.iteritems(files):
if not v: if file_instances is None:
# if the file field is nullable, skip None values
continue
for file_instance in file_instances:
if file_instance is None:
# if the file field is nullable, skip None values
continue continue
file_names = v if type(v) is list else [v] if file_instance.closed is True:
for n in file_names: raise ApiValueError(
with open(n, 'rb') as f: "Cannot read a closed file. The passed in file_type "
filename = os.path.basename(f.name) "for %s must be open." % param_name
filedata = f.read() )
mimetype = (mimetypes.guess_type(filename)[0] or filename = os.path.basename(file_instance.name)
'application/octet-stream') filedata = file_instance.read()
params.append( mimetype = (mimetypes.guess_type(filename)[0] or
tuple([k, tuple([filename, filedata, mimetype])])) 'application/octet-stream')
params.append(
tuple([param_name, tuple([filename, filedata, mimetype])]))
file_instance.close()
return params return params
@@ -538,133 +541,3 @@ class ApiClient(object):
raise ApiValueError( raise ApiValueError(
'Authentication token must be in `query` or `header`' 'Authentication token must be in `query` or `header`'
) )
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
except ValueError as exc:
raise ApiValueError(str(exc))
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal, ModelSimple or ModelNormal
:return: model object.
"""
if issubclass(klass, ModelSimple):
value = self.__deserialize(data, klass.openapi_types['value'])
return klass(value)
# code to handle ModelNormal
used_data = data
if not isinstance(data, (list, dict)):
used_data = [data]
keyword_args = {}
positional_args = []
if klass.openapi_types is not None:
for attr, attr_type in six.iteritems(klass.openapi_types):
if (data is not None and
klass.attribute_map[attr] in used_data):
value = used_data[klass.attribute_map[attr]]
keyword_args[attr] = self.__deserialize(value, attr_type)
end_index = None
argspec = inspect.getargspec(getattr(klass, '__init__'))
if argspec.defaults:
end_index = -len(argspec.defaults)
required_positional_args = argspec.args[1:end_index]
for index, req_positional_arg in enumerate(required_positional_args):
if keyword_args and req_positional_arg in keyword_args:
positional_args.append(keyword_args[req_positional_arg])
del keyword_args[req_positional_arg]
elif (not keyword_args and index < len(used_data) and
isinstance(used_data, list)):
positional_args.append(used_data[index])
instance = klass(*positional_args, **keyword_args)
if hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance

View File

@@ -7,14 +7,29 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from {{packageName}}.exceptions import ApiValueError # noqa: F401 from {{packageName}}.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from {{packageName}}.model_utils import ( # noqa: F401 from {{packageName}}.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
{{#models}}{{#model}}{{#imports}}{{.}}
{{/imports}}{{/model}}{{/models}}
{{#models}} {{#models}}
{{#model}} {{#model}}

View File

@@ -3,10 +3,22 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
{{#requiredVars}}{{^defaultValue}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}} {{#requiredVars}}
{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{#defaultValue}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}} {{^defaultValue}}
{{/defaultValue}}{{/requiredVars}}{{#optionalVars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}} **{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}}
{{/defaultValue}}
{{/requiredVars}}
{{#requiredVars}}
{{#defaultValue}}
**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}}
{{/defaultValue}}
{{/requiredVars}}
{{#optionalVars}}
**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}}
{{/optionalVars}} {{/optionalVars}}
{{#additionalPropertiesType}}
**any string name** | **{{additionalPropertiesType}}** | any string name can be used but the value must be the correct type | [optional]
{{/additionalPropertiesType}}
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,5 +1,5 @@
allowed_values = { allowed_values = {
{{#vars}} {{#allVars}}
{{#isEnum}} {{#isEnum}}
('{{name}}',): { ('{{name}}',): {
{{#isNullable}} {{#isNullable}}
@@ -7,10 +7,10 @@
{{/isNullable}} {{/isNullable}}
{{#allowableValues}} {{#allowableValues}}
{{#enumVars}} {{#enumVars}}
'{{name}}': {{{value}}}{{^-last}},{{/-last}} '{{name}}': {{{value}}},
{{/enumVars}} {{/enumVars}}
{{/allowableValues}} {{/allowableValues}}
}, },
{{/isEnum}} {{/isEnum}}
{{/vars}} {{/allVars}}
} }

View File

@@ -1,25 +1,42 @@
openapi_types = { openapi_types = {
{{#vars}} {{#allVars}}
'{{name}}': '{{{dataType}}}'{{#hasMore}},{{/hasMore}} '{{name}}': ({{{dataType}}},), # noqa: E501
{{/vars}} {{/allVars}}
} }
validations = { validations = {
{{#vars}} {{#allVars}}
{{#hasValidation}} {{#hasValidation}}
('{{name}}',): { ('{{name}}',): {
{{#maxLength}} {{#maxLength}}
'max_length': {{maxLength}},{{/maxLength}}{{#minLength}} 'max_length': {{maxLength}},
'min_length': {{minLength}},{{/minLength}}{{#maxItems}} {{/maxLength}}
'max_items': {{maxItems}},{{/maxItems}}{{#minItems}} {{#minLength}}
'min_items': {{minItems}},{{/minItems}}{{#maximum}} 'min_length': {{minLength}},
{{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}},{{/maximum}}{{#minimum}} {{/minLength}}
{{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}},{{/minimum}}{{#pattern}} {{#maxItems}}
'max_items': {{maxItems}},
{{/maxItems}}
{{#minItems}}
'min_items': {{minItems}},
{{/minItems}}
{{#maximum}}
{{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}},
{{/maximum}}
{{#minimum}}
{{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}},
{{/minimum}}
{{#pattern}}
'regex': { 'regex': {
'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}} 'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}}
{{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}} {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}}
},{{/pattern}} },
{{/pattern}}
}, },
{{/hasValidation}} {{/hasValidation}}
{{/vars}} {{/allVars}}
} }
additional_properties_type = {{#additionalPropertiesType}}({{{additionalPropertiesType}}},) # noqa: E501{{/additionalPropertiesType}}{{^additionalPropertiesType}}None{{/additionalPropertiesType}}
discriminator = {{#discriminator}}'{{{discriminatorName}}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}}

View File

@@ -4,4 +4,6 @@
and the for var_name this is (var_name,). The value is a dict and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.

View File

@@ -1,76 +1,126 @@
def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): # noqa: E501 def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{#defaultValue}}, {{name}}={{{defaultValue}}}{{/defaultValue}}{{/requiredVars}}, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
"""{{classname}} - a model defined in OpenAPI""" # noqa: E501 """{{classname}} - a model defined in OpenAPI
{{#vars}}{{#-first}}
{{/-first}} {{#requiredVars}}{{^hasMore}} Args:{{/hasMore}}{{/requiredVars}}{{#requiredVars}}{{^defaultValue}}
self._{{name}} = None {{name}} ({{{dataType}}}):{{#description}} {{description}}{{/description}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{^hasMore}}
{{/vars}} {{/hasMore}}{{/requiredVars}}
self.discriminator = {{#discriminator}}'{{{discriminatorName}}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}} Keyword Args:{{#requiredVars}}{{#defaultValue}}
{{#vars}}{{#-first}} {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}] # noqa: E501{{/defaultValue}}{{/requiredVars}}
{{/-first}} _check_type (bool): if True, values for parameters in openapi_types
{{#required}} will be type checked and a TypeError will be
self.{{name}} = {{name}} raised if the wrong type is input.
{{/required}} Defaults to True
{{^required}} _path_to_item (tuple/list): This is a list of keys or values to
{{#isNullable}} drill down to the model in received_data
self.{{name}} = {{name}} when deserializing a response
{{/isNullable}} _from_server (bool): True if the data is from the server
{{^isNullable}} False if the data is from the client (default)
if {{name}} is not None: _configuration (Configuration): the instance to use when
self.{{name}} = ( deserializing a file_type parameter.
{{name}} If passed, type conversion is attempted
If omitted no type conversion is done.{{#optionalVars}}
{{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501{{/optionalVars}}
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
{{#requiredVars}}
self.__set_item('{{name}}', {{name}})
{{/requiredVars}}
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
{{/isNullable}} elif self.additional_properties_type is not None:
{{/required}} required_types_mixed = self.additional_properties_type
{{/vars}}
{{#vars}} if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
{{#allVars}}
@property @property
def {{name}}(self): def {{name}}(self):
"""Gets the {{name}} of this {{classname}}. # noqa: E501 """Gets the {{name}} of this {{classname}}. # noqa: E501
{{#description}} {{#description}}
{{{description}}} # noqa: E501 {{{description}}} # noqa: E501
{{/description}} {{/description}}
:return: The {{name}} of this {{classname}}. # noqa: E501 Returns:
:rtype: {{dataType}} ({{{dataType}}}): The {{name}} of this {{classname}}. # noqa: E501
""" """
return self._{{name}} return self.__get_item('{{name}}')
@{{name}}.setter @{{name}}.setter
def {{name}}(self, {{name}}): # noqa: E501 def {{name}}(self, value):
"""Sets the {{name}} of this {{classname}}. """Sets the {{name}} of this {{classname}}. # noqa: E501
{{#description}} {{#description}}
{{{description}}} # noqa: E501 {{{description}}} # noqa: E501
{{/description}} {{/description}}
:param {{name}}: The {{name}} of this {{classname}}. # noqa: E501
:type: {{dataType}}
""" """
{{^isNullable}} return self.__set_item('{{name}}', value)
{{#required}} {{/allVars}}
if {{name}} is None:
raise ApiValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501
{{/required}}
{{/isNullable}}
{{#isEnum}}
check_allowed_values(
self.allowed_values,
('{{name}}',),
{{name}},
self.validations
)
{{/isEnum}}
{{#hasValidation}}
check_validations(
self.validations,
('{{name}}',),
{{name}}
)
{{/hasValidation}}
self._{{name}} = (
{{name}}
)
{{/vars}}

View File

@@ -16,14 +16,14 @@ class {{classname}}(ModelNormal):
{{> python-experimental/model_templates/classvar_allowed }} {{> python-experimental/model_templates/classvar_allowed }}
attribute_map = { attribute_map = {
{{#vars}} {{#allVars}}
'{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} # noqa: E501 '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} # noqa: E501
{{/vars}} {{/allVars}}
} }
{{#discriminator}} {{#discriminator}}
discriminator_value_class_map = { discriminator_value_class_map = {
{{#children}}'{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': '{{{classname}}}'{{^-last}}, {{#children}}'{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}': {{{classname}}}{{^-last}},
{{/-last}}{{/children}} {{/-last}}{{/children}}
} }
{{/discriminator}} {{/discriminator}}
@@ -32,36 +32,19 @@ class {{classname}}(ModelNormal):
{{> python-experimental/model_templates/methods_init_properties }} {{> python-experimental/model_templates/methods_init_properties }}
{{#discriminator}} {{#discriminator}}
def get_real_child_model(self, data): @classmethod
"""Returns the real base class specified by the discriminator""" def get_real_child_model(cls, data):
discriminator_key = self.attribute_map[self.discriminator] """Returns the real base class specified by the discriminator
We assume that data has javascript keys
"""
discriminator_key = cls.attribute_map[cls.discriminator]
discriminator_value = data[discriminator_key] discriminator_value = data[discriminator_key]
return self.discriminator_value_class_map.get(discriminator_value) return cls.discriminator_value_class_map.get(discriminator_value)
{{/discriminator}} {{/discriminator}}
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -76,7 +59,22 @@ class {{classname}}(ModelNormal):
if not isinstance(other, {{classname}}): if not isinstance(other, {{classname}}):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -16,7 +16,7 @@ class {{classname}}(ModelSimple):
{{> python-experimental/model_templates/methods_init_properties }} {{> python-experimental/model_templates/methods_init_properties }}
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
return str(self._value) return str(self.value)
def __repr__(self): def __repr__(self):
"""For `print` and `pprint`""" """For `print` and `pprint`"""
@@ -27,7 +27,19 @@ class {{classname}}(ModelSimple):
if not isinstance(other, {{classname}}): if not isinstance(other, {{classname}}):
return False return False
return self.__dict__ == other.__dict__ this_val = self._data_store['value']
that_val = other._data_store['value']
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -1,13 +1,162 @@
# coding: utf-8 # coding: utf-8
{{>partial_header}} {{>partial_header}}
import copy
from datetime import date, datetime # noqa: F401
import inspect
import os
import re import re
import tempfile
from {{packageName}}.exceptions import ApiValueError from dateutil.parser import parse
import six
from {{packageName}}.exceptions import (
ApiKeyError,
ApiTypeError,
ApiValueError,
)
none_type = type(None)
if six.PY3:
import io
file_type = io.IOBase
# these are needed for when other modules import str and int from here
str = str
int = int
else:
file_type = file # noqa: F821
str_py2 = str
unicode_py2 = unicode # noqa: F821
long_py2 = long # noqa: F821
int_py2 = int
# this requires that the future library is installed
from builtins import int, str
def check_allowed_values(allowed_values, input_variable_path, input_values, class OpenApiModel(object):
validations): """The base class for all OpenAPIModels"""
class ModelSimple(OpenApiModel):
"""the parent class of models whose type != object in their
swagger/openapi"""
class ModelNormal(OpenApiModel):
"""the parent class of models whose type == object in their
swagger/openapi"""
COERCION_INDEX_BY_TYPE = {
ModelNormal: 0,
ModelSimple: 1,
none_type: 2,
list: 3,
dict: 4,
float: 5,
int: 6,
bool: 7,
datetime: 8,
date: 9,
str: 10,
file_type: 11,
}
# these are used to limit what type conversions we try to do
# when we have a valid type already and we want to try converting
# to another type
UPCONVERSION_TYPE_PAIRS = (
(str, datetime),
(str, date),
(list, ModelNormal),
(dict, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
)
COERCIBLE_TYPE_PAIRS = {
False: ( # client instantiation of a model with client data
# (dict, ModelNormal),
# (list, ModelNormal),
# (str, ModelSimple),
# (int, ModelSimple),
# (float, ModelSimple),
# (list, ModelSimple),
# (str, int),
# (str, float),
# (str, datetime),
# (str, date),
# (int, str),
# (float, str),
),
True: ( # server -> client data
(dict, ModelNormal),
(list, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
# (str, int),
# (str, float),
(str, datetime),
(str, date),
# (int, str),
# (float, str),
(str, file_type)
),
}
def get_simple_class(input_value):
"""Returns an input_value's simple class that we will use for type checking
Python2:
float and int will return int, where int is the python3 int backport
str and unicode will return str, where str is the python3 str backport
Note: float and int ARE both instances of int backport
Note: str_py2 and unicode_py2 are NOT both instances of str backport
Args:
input_value (class/class_instance): the item for which we will return
the simple class
"""
if isinstance(input_value, type):
# input_value is a class
return input_value
elif isinstance(input_value, tuple):
return tuple
elif isinstance(input_value, list):
return list
elif isinstance(input_value, dict):
return dict
elif isinstance(input_value, none_type):
return none_type
elif isinstance(input_value, file_type):
return file_type
elif isinstance(input_value, bool):
# this must be higher than the int check because
# isinstance(True, int) == True
return bool
elif isinstance(input_value, int):
# for python2 input_value==long_instance -> return int
# where int is the python3 int backport
return int
elif isinstance(input_value, datetime):
# this must be higher than the date check because
# isinstance(datetime_instance, date) == True
return datetime
elif isinstance(input_value, date):
return date
elif (six.PY2 and isinstance(input_value, (str_py2, unicode_py2, str)) or
isinstance(input_value, str)):
return str
return type(input_value)
def check_allowed_values(allowed_values, input_variable_path, input_values):
"""Raises an exception if the input_values are not allowed """Raises an exception if the input_values are not allowed
Args: Args:
@@ -15,14 +164,9 @@ def check_allowed_values(allowed_values, input_variable_path, input_values,
input_variable_path (tuple): the path to the input variable input_variable_path (tuple): the path to the input variable
input_values (list/str/int/float/date/datetime): the values that we input_values (list/str/int/float/date/datetime): the values that we
are checking to see if they are in allowed_values are checking to see if they are in allowed_values
validations (dict): the validations dict
""" """
min_collection_length = (
validations.get(input_variable_path, {}).get('min_length') or
validations.get(input_variable_path, {}).get('min_items', 0))
these_allowed_values = list(allowed_values[input_variable_path].values()) these_allowed_values = list(allowed_values[input_variable_path].values())
if (isinstance(input_values, list) if (isinstance(input_values, list)
and len(input_values) > min_collection_length
and not set(input_values).issubset( and not set(input_values).issubset(
set(these_allowed_values))): set(these_allowed_values))):
invalid_values = ", ".join( invalid_values = ", ".join(
@@ -36,7 +180,6 @@ def check_allowed_values(allowed_values, input_variable_path, input_values,
) )
) )
elif (isinstance(input_values, dict) elif (isinstance(input_values, dict)
and len(input_values) > min_collection_length
and not set( and not set(
input_values.keys()).issubset(set(these_allowed_values))): input_values.keys()).issubset(set(these_allowed_values))):
invalid_values = ", ".join( invalid_values = ", ".join(
@@ -111,8 +254,21 @@ def check_validations(validations, input_variable_path, input_values):
) )
) )
items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum',
'inclusive_minimum')
if (any(item in current_validations for item in items)):
if isinstance(input_values, list):
max_val = max(input_values)
min_val = min(input_values)
elif isinstance(input_values, dict):
max_val = max(input_values.values())
min_val = min(input_values.values())
else:
max_val = input_values
min_val = input_values
if ('exclusive_maximum' in current_validations and if ('exclusive_maximum' in current_validations and
input_values >= current_validations['exclusive_maximum']): max_val >= current_validations['exclusive_maximum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value less than `%s`" % ( "Invalid value for `%s`, must be a value less than `%s`" % (
input_variable_path[0], input_variable_path[0],
@@ -121,7 +277,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('inclusive_maximum' in current_validations and if ('inclusive_maximum' in current_validations and
input_values > current_validations['inclusive_maximum']): max_val > current_validations['inclusive_maximum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value less than or equal to " "Invalid value for `%s`, must be a value less than or equal to "
"`%s`" % ( "`%s`" % (
@@ -131,7 +287,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('exclusive_minimum' in current_validations and if ('exclusive_minimum' in current_validations and
input_values <= current_validations['exclusive_minimum']): min_val <= current_validations['exclusive_minimum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value greater than `%s`" % "Invalid value for `%s`, must be a value greater than `%s`" %
( (
@@ -141,7 +297,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('inclusive_minimum' in current_validations and if ('inclusive_minimum' in current_validations and
input_values < current_validations['inclusive_minimum']): min_val < current_validations['inclusive_minimum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value greater than or equal " "Invalid value for `%s`, must be a value greater than or equal "
"to `%s`" % ( "to `%s`" % (
@@ -163,13 +319,550 @@ def check_validations(validations, input_variable_path, input_values):
) )
class ModelSimple(object): def order_response_types(required_types):
# the parent class of models whose type != object in their swagger/openapi """Returns the required types sorted in coercion order
# spec
pass Args:
required_types (list/tuple): collection of classes or instance of
list or dict with classs information inside it
Returns:
(list): coercion order sorted collection of classes or instance
of list or dict with classs information inside it
"""
def index_getter(class_or_instance):
if isinstance(class_or_instance, list):
return COERCION_INDEX_BY_TYPE[list]
elif isinstance(class_or_instance, dict):
return COERCION_INDEX_BY_TYPE[dict]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelNormal)):
return COERCION_INDEX_BY_TYPE[ModelNormal]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelSimple)):
return COERCION_INDEX_BY_TYPE[ModelSimple]
return COERCION_INDEX_BY_TYPE[class_or_instance]
sorted_types = sorted(
required_types,
key=lambda class_or_instance: index_getter(class_or_instance)
)
return sorted_types
class ModelNormal(object): def remove_uncoercible(required_types_classes, current_item, from_server,
# the parent class of models whose type == object in their swagger/openapi must_convert=True):
# spec """Only keeps the type conversions that are possible
pass
Args:
required_types_classes (tuple): tuple of classes that are required
these should be ordered by COERCION_INDEX_BY_TYPE
from_server (bool): a boolean of whether the data is from the server
if false, the data is from the client
current_item (any): the current item to be converted
Keyword Args:
must_convert (bool): if True the item to convert is of the wrong
type and we want a big list of coercibles
if False, we want a limited list of coercibles
Returns:
(list): the remaining coercible required types, classes only
"""
current_type_simple = get_simple_class(current_item)
results_classes = []
for required_type_class in required_types_classes:
# convert our models to OpenApiModel
required_type_class_simplified = required_type_class
if isinstance(required_type_class_simplified, type):
if issubclass(required_type_class_simplified, ModelNormal):
required_type_class_simplified = ModelNormal
elif issubclass(required_type_class_simplified, ModelSimple):
required_type_class_simplified = ModelSimple
if required_type_class_simplified == current_type_simple:
# don't consider converting to one's own class
continue
class_pair = (current_type_simple, required_type_class_simplified)
if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[from_server]:
results_classes.append(required_type_class)
elif class_pair in UPCONVERSION_TYPE_PAIRS:
results_classes.append(required_type_class)
return results_classes
def get_required_type_classes(required_types_mixed):
"""Converts the tuple required_types into a tuple and a dict described
below
Args:
required_types_mixed (tuple/list): will contain either classes or
instance of list or dict
Returns:
(valid_classes, dict_valid_class_to_child_types_mixed):
valid_classes (tuple): the valid classes that the current item
should be
dict_valid_class_to_child_types_mixed (doct):
valid_class (class): this is the key
child_types_mixed (list/dict/tuple): describes the valid child
types
"""
valid_classes = []
child_req_types_by_current_type = {}
for required_type in required_types_mixed:
if isinstance(required_type, list):
valid_classes.append(list)
child_req_types_by_current_type[list] = required_type
elif isinstance(required_type, tuple):
valid_classes.append(tuple)
child_req_types_by_current_type[tuple] = required_type
elif isinstance(required_type, dict):
valid_classes.append(dict)
child_req_types_by_current_type[dict] = required_type[str]
else:
valid_classes.append(required_type)
return tuple(valid_classes), child_req_types_by_current_type
def change_keys_js_to_python(input_dict, model_class):
"""
Converts from javascript_key keys in the input_dict to python_keys in
the output dict using the mapping in model_class
"""
output_dict = {}
reversed_attr_map = {value: key for key, value in
six.iteritems(model_class.attribute_map)}
for javascript_key, value in six.iteritems(input_dict):
python_key = reversed_attr_map.get(javascript_key)
if python_key is None:
# if the key is unknown, it is in error or it is an
# additionalProperties variable
python_key = javascript_key
output_dict[python_key] = value
return output_dict
def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
error_msg = type_error_message(
var_name=path_to_item[-1],
var_value=var_value,
valid_classes=valid_classes,
key_type=key_type
)
return ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=valid_classes,
key_type=key_type
)
def deserialize_primitive(data, klass, path_to_item):
"""Deserializes string to primitive type.
:param data: str/int/float
:param klass: str/class the class to convert to
:return: int, float, str, bool, date, datetime
"""
additional_message = ""
try:
if klass in {datetime, date}:
additional_message = (
"If you need your parameter to have a fallback "
"string value, please set its type as `type: {}` in your "
"spec. That allows the value to be any type. "
)
if klass == datetime:
if len(data) < 8:
raise ValueError("This is not a datetime")
# The string should be in iso8601 datetime format.
parsed_datetime = parse(data)
date_only = (
parsed_datetime.hour == 0 and
parsed_datetime.minute == 0 and
parsed_datetime.second == 0 and
parsed_datetime.tzinfo is None and
8 <= len(data) <= 10
)
if date_only:
raise ValueError("This is a date, not a datetime")
return parsed_datetime
elif klass == date:
if len(data) < 8:
raise ValueError("This is not a date")
return parse(data).date()
else:
converted_value = klass(data)
if isinstance(data, str) and klass == float:
if str(converted_value) != data:
# '7' -> 7.0 -> '7.0' != '7'
raise ValueError('This is not a float')
return converted_value
except (OverflowError, ValueError):
# parse can raise OverflowError
raise ApiValueError(
"{0}Failed to parse {1} as {2}".format(
additional_message, repr(data), get_py3_class_name(klass)
),
path_to_item=path_to_item
)
def deserialize_model(model_data, model_class, path_to_item, check_type,
configuration, from_server):
"""Deserializes model_data to model instance.
Args:
model_data (list/dict): data to instantiate the model
model_class (OpenApiModel): the model class
path_to_item (list): path to the model in the received data
check_type (bool): whether to check the data tupe for the values in
the model
configuration (Configuration): the instance to use to convert files
from_server (bool): True if the data is from the server
False if the data is from the client
Returns:
model instance
Raise:
ApiTypeError
ApiValueError
ApiKeyError
"""
fixed_model_data = copy.deepcopy(model_data)
if isinstance(fixed_model_data, dict):
fixed_model_data = change_keys_js_to_python(fixed_model_data,
model_class)
kw_args = dict(_check_type=check_type,
_path_to_item=path_to_item,
_configuration=configuration,
_from_server=from_server)
if hasattr(model_class, 'get_real_child_model'):
# discriminator case
discriminator_class = model_class.get_real_child_model(model_data)
if discriminator_class:
if isinstance(model_data, list):
instance = discriminator_class(*model_data, **kw_args)
elif isinstance(model_data, dict):
fixed_model_data = change_keys_js_to_python(
fixed_model_data,
discriminator_class
)
kw_args.update(fixed_model_data)
instance = discriminator_class(**kw_args)
else:
# all other cases
if isinstance(model_data, list):
instance = model_class(*model_data, **kw_args)
if isinstance(model_data, dict):
fixed_model_data = change_keys_js_to_python(fixed_model_data,
model_class)
kw_args.update(fixed_model_data)
instance = model_class(**kw_args)
else:
instance = model_class(model_data, **kw_args)
return instance
def deserialize_file(response_data, configuration, content_disposition=None):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
Args:
param response_data (str): the file data to write
configuration (Configuration): the instance to use to convert files
Keyword Args:
content_disposition (str): the value of the Content-Disposition
header
Returns:
(file_type): the deserialized file which is open
The user is responsible for closing and reading the file
"""
fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
os.close(fd)
os.remove(path)
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
if six.PY3 and isinstance(response_data, str):
# in python3 change str to bytes so we can write it
response_data = response_data.encode('utf-8')
f.write(response_data)
f = open(path, "rb")
return f
def attempt_convert_item(input_value, valid_classes, path_to_item,
configuration, from_server, key_type=False,
must_convert=False, check_type=True):
"""
Args:
input_value (any): the data to convert
valid_classes (any): the classes that are valid
path_to_item (list): the path to the item to convert
configuration (Configuration): the instance to use to convert files
from_server (bool): True if data is from the server, False is data is
from the client
key_type (bool): if True we need to convert a key type (not supported)
must_convert (bool): if True we must convert
check_type (bool): if True we check the type or the returned data in
ModelNormal and ModelSimple instances
Returns:
instance (any) the fixed item
Raises:
ApiTypeError
ApiValueError
ApiKeyError
"""
valid_classes_ordered = order_response_types(valid_classes)
valid_classes_coercible = remove_uncoercible(
valid_classes_ordered, input_value, from_server)
if not valid_classes_coercible or key_type:
# we do not handle keytype errors, json will take care
# of this for us
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=key_type)
for valid_class in valid_classes_coercible:
try:
if issubclass(valid_class, OpenApiModel):
return deserialize_model(input_value, valid_class,
path_to_item, check_type,
configuration, from_server)
elif valid_class == file_type:
return deserialize_file(input_value, configuration)
return deserialize_primitive(input_value, valid_class,
path_to_item)
except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
if must_convert:
raise conversion_exc
# if we have conversion errors when must_convert == False
# we ignore the exception and move on to the next class
continue
# we were unable to convert, must_convert == False
return input_value
def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
from_server, _check_type, configuration=None):
"""Raises a TypeError is there is a problem, otherwise returns value
Args:
input_value (any): the data to validate/convert
required_types_mixed (list/dict/tuple): A list of
valid classes, or a list tuples of valid classes, or a dict where
the value is a tuple of value classes
path_to_item: (list) the path to the data being validated
this stores a list of keys or indices to get to the data being
validated
from_server (bool): True if data is from the server
False if data is from the client
_check_type: (boolean) if true, type will be checked and conversion
will be attempted.
configuration: (Configuration): the configuration class to use
when converting file_type items.
If passed, conversion will be attempted when possible
If not passed, no conversions will be attempted and
exceptions will be raised
Returns:
the correctly typed value
Raises:
ApiTypeError
"""
results = get_required_type_classes(required_types_mixed)
valid_classes, child_req_types_by_current_type = results
input_class_simple = get_simple_class(input_value)
valid_type = input_class_simple in set(valid_classes)
if not valid_type:
if configuration:
# if input_value is not valid_type try to convert it
converted_instance = attempt_convert_item(
input_value,
valid_classes,
path_to_item,
configuration,
from_server,
key_type=False,
must_convert=True
)
return converted_instance
else:
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=False)
# input_value's type is in valid_classes
if len(valid_classes) > 1 and configuration:
# there are valid classes which are not the current class
valid_classes_coercible = remove_uncoercible(
valid_classes, input_value, from_server, must_convert=False)
if valid_classes_coercible:
converted_instance = attempt_convert_item(
input_value,
valid_classes_coercible,
path_to_item,
configuration,
from_server,
key_type=False,
must_convert=False
)
return converted_instance
if child_req_types_by_current_type == {}:
# all types are of the required types and there are no more inner
# variables left to look at
return input_value
inner_required_types = child_req_types_by_current_type.get(
type(input_value)
)
if inner_required_types is None:
# for this type, there are not more inner variables left to look at
return input_value
if isinstance(input_value, list):
if input_value == []:
# allow an empty list
return input_value
for index, inner_value in enumerate(input_value):
inner_path = list(path_to_item)
inner_path.append(index)
input_value[index] = validate_and_convert_types(
inner_value,
inner_required_types,
inner_path,
from_server,
_check_type,
configuration=configuration
)
elif isinstance(input_value, dict):
if input_value == {}:
# allow an empty dict
return input_value
for inner_key, inner_val in six.iteritems(input_value):
inner_path = list(path_to_item)
inner_path.append(inner_key)
if get_simple_class(inner_key) != str:
raise get_type_error(inner_key, inner_path, valid_classes,
key_type=True)
input_value[inner_key] = validate_and_convert_types(
inner_val,
inner_required_types,
inner_path,
from_server,
_check_type,
configuration=configuration
)
return input_value
def model_to_dict(model_instance, serialize=True):
"""Returns the model properties as a dict
Args:
model_instance (one of your model instances): the model instance that
will be converted to a dict.
Keyword Args:
serialize (bool): if True, the keys in the dict will be values from
attribute_map
"""
result = {}
for attr, value in six.iteritems(model_instance._data_store):
if serialize:
# we use get here because additional property key names do not
# exist in attribute_map
attr = model_instance.attribute_map.get(attr, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: model_to_dict(x, serialize=serialize)
if hasattr(x, '_data_store') else x, value
))
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0],
model_to_dict(item[1], serialize=serialize))
if hasattr(item[1], '_data_store') else item,
value.items()
))
elif hasattr(value, '_data_store'):
result[attr] = model_to_dict(value, serialize=serialize)
else:
result[attr] = value
return result
def type_error_message(var_value=None, var_name=None, valid_classes=None,
key_type=None):
"""
Keyword Args:
var_value (any): the variable which has the type_error
var_name (str): the name of the variable which has the typ error
valid_classes (tuple): the accepted classes for current_item's
value
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
"""
key_or_value = 'value'
if key_type:
key_or_value = 'key'
valid_classes_phrase = get_valid_classes_phrase(valid_classes)
msg = (
"Invalid type for variable '{0}'. Required {1} type {2} and "
"passed type was {3}".format(
var_name,
key_or_value,
valid_classes_phrase,
type(var_value).__name__,
)
)
return msg
def get_valid_classes_phrase(input_classes):
"""Returns a string phrase describing what types are allowed
Note: Adds the extra valid classes in python2
"""
all_classes = list(input_classes)
if six.PY2 and str in input_classes:
all_classes.extend([str_py2, unicode_py2])
if six.PY2 and int in input_classes:
all_classes.extend([int_py2, long_py2])
all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
all_class_names = [cls.__name__ for cls in all_classes]
if len(all_class_names) == 1:
return 'is {0}'.format(all_class_names[0])
return "is one of [{0}]".format(", ".join(all_class_names))
def get_py3_class_name(input_class):
if six.PY2:
if input_class == str:
return 'str'
elif input_class == int:
return 'int'
return input_class.__name__

View File

@@ -0,0 +1,6 @@
certifi >= 14.05.14
future; python_version<="2.7"
six >= 1.10
python_dateutil >= 2.5.3
setuptools >= 21.0.0
urllib3 >= 1.15.1

View File

@@ -0,0 +1,45 @@
# coding: utf-8
{{>partial_header}}
from setuptools import setup, find_packages # noqa: H301
NAME = "{{{projectName}}}"
VERSION = "{{packageVersion}}"
{{#apiInfo}}
{{#apis}}
{{^hasMore}}
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"]
{{#asyncio}}
REQUIRES.append("aiohttp >= 3.0.0")
{{/asyncio}}
{{#tornado}}
REQUIRES.append("tornado>=4.2,<5")
{{/tornado}}
EXTRAS = {':python_version <= "2.7"': ['future']}
setup(
name=NAME,
version=VERSION,
description="{{appName}}",
author_email="{{infoEmail}}",
url="{{packageUrl}}",
keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"],
install_requires=REQUIRES,
extras_require=EXTRAS,
packages=find_packages(exclude=["test", "tests"]),
include_package_data=True,
long_description="""\
{{appDescription}} # noqa: E501
"""
)
{{/hasMore}}
{{/apis}}
{{/apiInfo}}

View File

@@ -0,0 +1,13 @@
{{^asyncio}}
coverage>=4.0.3
nose>=1.3.7
{{/asyncio}}
{{#asyncio}}
pytest>=3.6.0
pytest-cov>=2.6.1
{{/asyncio}}
pluggy>=0.3.1
py>=1.4.31
randomize>=0.13
mock; python_version<="2.7"

View File

@@ -1,4 +1,5 @@
certifi >= 14.05.14 certifi >= 14.05.14
future; python_version<="2.7"
six >= 1.10 six >= 1.10
python_dateutil >= 2.5.3 python_dateutil >= 2.5.3
setuptools >= 21.0.0 setuptools >= 21.0.0

View File

@@ -0,0 +1,296 @@
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.python;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.*;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.PythonClientExperimentalCodegen;
import org.testng.Assert;
import org.testng.annotations.Test;
@SuppressWarnings("static-method")
public class PythonClientExperimentalTest {
@Test(description = "convert a python model with dots")
public void modelTest() {
final OpenAPI openAPI= TestUtils.parseSpec("src/test/resources/2_0/v1beta3.json");
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
codegen.setOpenAPI(openAPI);
codegen.setOpenAPI(openAPI);
final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", openAPI.getComponents().getSchemas().get("v1beta3.Binding"));
Assert.assertEquals(simpleName.name, "v1beta3.Binding");
Assert.assertEquals(simpleName.classname, "V1beta3Binding");
Assert.assertEquals(simpleName.classVarName, "v1beta3_binding");
codegen.setOpenAPI(openAPI);
final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", openAPI.getComponents().getSchemas().get("v1beta3.ComponentStatus"));
Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus");
Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus");
Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status");
final String path = "/api/v1beta3/namespaces/{namespaces}/bindings";
final Operation operation = openAPI.getPaths().get(path).getPost();
final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, null);
Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding");
Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding");
}
@Test(description = "convert a simple java model")
public void simpleModelTest() {
final Schema schema = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
.addProperties("name", new StringSchema())
.addProperties("createdAt", new DateTimeSchema())
.addRequiredItem("id")
.addRequiredItem("name");
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", schema);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 3);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "name");
Assert.assertEquals(property2.dataType, "str");
Assert.assertEquals(property2.name, "name");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "str");
Assert.assertTrue(property2.hasMore);
Assert.assertTrue(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
final CodegenProperty property3 = cm.vars.get(2);
Assert.assertEquals(property3.baseName, "createdAt");
Assert.assertEquals(property3.dataType, "datetime");
Assert.assertEquals(property3.name, "created_at");
Assert.assertNull(property3.defaultValue);
Assert.assertEquals(property3.baseType, "datetime");
Assert.assertFalse(property3.hasMore);
Assert.assertFalse(property3.required);
}
@Test(description = "convert a model with list property")
public void listPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
.addProperties("urls", new ArraySchema()
.items(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 2);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "id");
Assert.assertEquals(property1.dataType, "int");
Assert.assertEquals(property1.name, "id");
Assert.assertNull(property1.defaultValue);
Assert.assertEquals(property1.baseType, "int");
Assert.assertTrue(property1.hasMore);
Assert.assertTrue(property1.required);
Assert.assertTrue(property1.isPrimitiveType);
final CodegenProperty property2 = cm.vars.get(1);
Assert.assertEquals(property2.baseName, "urls");
Assert.assertEquals(property2.dataType, "[str]");
Assert.assertEquals(property2.name, "urls");
Assert.assertNull(property2.defaultValue);
Assert.assertEquals(property2.baseType, "list");
Assert.assertFalse(property2.hasMore);
Assert.assertEquals(property2.containerType, "array");
Assert.assertFalse(property2.required);
Assert.assertTrue(property2.isPrimitiveType);
Assert.assertTrue(property2.isContainer);
}
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("translations", new MapSchema()
.additionalProperties(new StringSchema()))
.addRequiredItem("id");
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "translations");
Assert.assertEquals(property1.dataType, "{str: (str,)}");
Assert.assertEquals(property1.name, "translations");
Assert.assertEquals(property1.baseType, "dict");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
Assert.assertTrue(property1.isPrimitiveType);
}
@Test(description = "convert a model with complex property")
public void complexPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.dataType, "Children");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "Children");
Assert.assertFalse(property1.required);
Assert.assertFalse(property1.isContainer);
}
@Test(description = "convert a model with complex list property")
public void complexListPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new ArraySchema()
.items(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.dataType, "[Children]");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "list");
Assert.assertEquals(property1.containerType, "array");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
@Test(description = "convert a model with complex map property")
public void complexMapPropertyTest() {
final Schema model = new Schema()
.description("a sample model")
.addProperties("children", new MapSchema()
.additionalProperties(new Schema().$ref("#/definitions/Children")));
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a sample model");
Assert.assertEquals(cm.vars.size(), 1);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
final CodegenProperty property1 = cm.vars.get(0);
Assert.assertEquals(property1.baseName, "children");
Assert.assertEquals(property1.complexType, "Children");
Assert.assertEquals(property1.dataType, "{str: (Children,)}");
Assert.assertEquals(property1.name, "children");
Assert.assertEquals(property1.baseType, "dict");
Assert.assertEquals(property1.containerType, "map");
Assert.assertFalse(property1.required);
Assert.assertTrue(property1.isContainer);
}
// should not start with 'null'. need help from the community to investigate further
@Test(description = "convert an array model")
public void arrayModelTest() {
final Schema model = new ArraySchema()
//.description()
.items(new Schema().$ref("#/definitions/Children"))
.description("an array model");
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "an array model");
Assert.assertEquals(cm.vars.size(), 0);
Assert.assertEquals(cm.parent, "list");
Assert.assertEquals(cm.imports.size(), 1);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
}
// should not start with 'null'. need help from the community to investigate further
@Test(description = "convert a map model")
public void mapModelTest() {
final Schema model = new Schema()
.description("a map model")
.additionalProperties(new Schema().$ref("#/definitions/Children"));
final DefaultCodegen codegen = new PythonClientExperimentalCodegen();
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
codegen.setOpenAPI(openAPI);
final CodegenModel cm = codegen.fromModel("sample", model);
Assert.assertEquals(cm.name, "sample");
Assert.assertEquals(cm.classname, "Sample");
Assert.assertEquals(cm.description, "a map model");
Assert.assertEquals(cm.vars.size(), 0);
Assert.assertEquals(cm.parent, "dict");
Assert.assertEquals(cm.imports.size(), 1);
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
}
}

View File

@@ -294,4 +294,4 @@ public class PythonTest {
Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1);
} }
} }

View File

@@ -269,6 +269,13 @@ paths:
description: file to upload description: file to upload
required: false required: false
type: file type: file
- name: files
in: formData
description: files to upload
required: false
type: array
items:
type: file
responses: responses:
'200': '200':
description: successful operation description: successful operation

View File

@@ -1,4 +1,5 @@
certifi >= 14.05.14 certifi >= 14.05.14
future; python_version<="2.7"
six >= 1.10 six >= 1.10
python_dateutil >= 2.5.3 python_dateutil >= 2.5.3
setuptools >= 21.0.0 setuptools >= 21.0.0

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **bool, date, datetime, dict, float, int, list, str** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **[bool, date, datetime, dict, float, int, list, str]** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -3,17 +3,17 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**map_string** | **dict(str, str)** | | [optional] **map_string** | **{str: (str,)}** | | [optional]
**map_number** | **dict(str, float)** | | [optional] **map_number** | **{str: (float,)}** | | [optional]
**map_integer** | **dict(str, int)** | | [optional] **map_integer** | **{str: (int,)}** | | [optional]
**map_boolean** | **dict(str, bool)** | | [optional] **map_boolean** | **{str: (bool,)}** | | [optional]
**map_array_integer** | **dict(str, list[int])** | | [optional] **map_array_integer** | **{str: ([int],)}** | | [optional]
**map_array_anytype** | **dict(str, list[object])** | | [optional] **map_array_anytype** | **{str: ([bool, date, datetime, dict, float, int, list, str],)}** | | [optional]
**map_map_string** | **dict(str, dict(str, str))** | | [optional] **map_map_string** | **{str: ({str: (str,)},)}** | | [optional]
**map_map_anytype** | **dict(str, dict(str, object))** | | [optional] **map_map_anytype** | **{str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}** | | [optional]
**anytype_1** | [**object**](.md) | | [optional] **anytype_1** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional]
**anytype_2** | [**object**](.md) | | [optional] **anytype_2** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional]
**anytype_3** | [**object**](.md) | | [optional] **anytype_3** | [**bool, date, datetime, dict, float, int, list, str**](.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **int** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **float** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **{str: (bool, date, datetime, dict, float, int, list, str,)}** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,6 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | [optional] **name** | **str** | | [optional]
**any string name** | **str** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -3,7 +3,7 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**array_array_number** | **list[list[float]]** | | [optional] **array_array_number** | **[[float]]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -3,7 +3,7 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**array_number** | **list[float]** | | [optional] **array_number** | **[float]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -3,9 +3,9 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**array_of_string** | **list[str]** | | [optional] **array_of_string** | **[str]** | | [optional]
**array_array_of_integer** | **list[list[int]]** | | [optional] **array_array_of_integer** | **[[int]]** | | [optional]
**array_array_of_model** | **list[list[ReadOnlyFirst]]** | | [optional] **array_array_of_model** | **[[ReadOnlyFirst]]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,7 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**just_symbol** | **str** | | [optional] **just_symbol** | **str** | | [optional]
**array_enum** | **list[str]** | | [optional] **array_enum** | **[str]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -591,7 +591,7 @@ int32 = 56 # int | None (optional)
int64 = 56 # int | None (optional) int64 = 56 # int | None (optional)
float = 3.4 # float | None (optional) float = 3.4 # float | None (optional)
string = 'string_example' # str | None (optional) string = 'string_example' # str | None (optional)
binary = '/path/to/file' # file | None (optional) binary = open('/path/to/file', 'rb') # file_type | None (optional)
date = '2013-10-20' # date | None (optional) date = '2013-10-20' # date | None (optional)
date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional) date_time = '2013-10-20T19:20:30+01:00' # datetime | None (optional)
password = 'password_example' # str | None (optional) password = 'password_example' # str | None (optional)
@@ -617,7 +617,7 @@ Name | Type | Description | Notes
**int64** | **int**| None | [optional] **int64** | **int**| None | [optional]
**float** | **float**| None | [optional] **float** | **float**| None | [optional]
**string** | **str**| None | [optional] **string** | **str**| None | [optional]
**binary** | **file**| None | [optional] **binary** | **file_type**| None | [optional]
**date** | **date**| None | [optional] **date** | **date**| None | [optional]
**date_time** | **datetime**| None | [optional] **date_time** | **datetime**| None | [optional]
**password** | **str**| None | [optional] **password** | **str**| None | [optional]
@@ -662,13 +662,13 @@ from pprint import pprint
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.FakeApi() api_instance = petstore_api.FakeApi()
enum_header_string_array = ['enum_header_string_array_example'] # list[str] | Header parameter enum test (string array) (optional) enum_header_string_array = ['enum_header_string_array_example'] # [str] | Header parameter enum test (string array) (optional)
enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to '-efg') enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to '-efg')
enum_query_string_array = ['enum_query_string_array_example'] # list[str] | Query parameter enum test (string array) (optional) enum_query_string_array = ['enum_query_string_array_example'] # [str] | Query parameter enum test (string array) (optional)
enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to '-efg') enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to '-efg')
enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_integer = 56 # int | Query parameter enum test (double) (optional)
enum_query_double = 3.4 # float | Query parameter enum test (double) (optional) enum_query_double = 3.4 # float | Query parameter enum test (double) (optional)
enum_form_string_array = '$' # list[str] | Form parameter enum test (string array) (optional) (default to '$') enum_form_string_array = '$' # [str] | Form parameter enum test (string array) (optional) (default to '$')
enum_form_string = '-efg' # str | Form parameter enum test (string) (optional) (default to '-efg') enum_form_string = '-efg' # str | Form parameter enum test (string) (optional) (default to '-efg')
try: try:
@@ -682,13 +682,13 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**enum_header_string_array** | [**list[str]**](str.md)| Header parameter enum test (string array) | [optional] **enum_header_string_array** | [**[str]**](str.md)| Header parameter enum test (string array) | [optional]
**enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' **enum_header_string** | **str**| Header parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg'
**enum_query_string_array** | [**list[str]**](str.md)| Query parameter enum test (string array) | [optional] **enum_query_string_array** | [**[str]**](str.md)| Query parameter enum test (string array) | [optional]
**enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' **enum_query_string** | **str**| Query parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg'
**enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_integer** | **int**| Query parameter enum test (double) | [optional]
**enum_query_double** | **float**| Query parameter enum test (double) | [optional] **enum_query_double** | **float**| Query parameter enum test (double) | [optional]
**enum_form_string_array** | [**list[str]**](str.md)| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of '$' **enum_form_string_array** | [**[str]**](str.md)| Form parameter enum test (string array) | [optional] if omitted the server will use the default value of '$'
**enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg' **enum_form_string** | **str**| Form parameter enum test (string) | [optional] if omitted the server will use the default value of '-efg'
### Return type ### Return type
@@ -791,7 +791,7 @@ from pprint import pprint
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.FakeApi() api_instance = petstore_api.FakeApi()
param = {'key': 'param_example'} # dict(str, str) | request body param = {'key': 'param_example'} # {str: (str,)} | request body
try: try:
# test inline additionalProperties # test inline additionalProperties
@@ -804,7 +804,7 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**param** | [**dict(str, str)**](str.md)| request body | **param** | [**{str: (str,)}**](str.md)| request body |
### Return type ### Return type

View File

@@ -4,7 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**file** | [**File**](File.md) | | [optional] **file** | [**File**](File.md) | | [optional]
**files** | [**list[File]**](File.md) | | [optional] **files** | [**[File]**](File.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -13,7 +13,7 @@ Name | Type | Description | Notes
**float** | **float** | | [optional] **float** | **float** | | [optional]
**double** | **float** | | [optional] **double** | **float** | | [optional]
**string** | **str** | | [optional] **string** | **str** | | [optional]
**binary** | **file** | | [optional] **binary** | **file_type** | | [optional]
**date_time** | **datetime** | | [optional] **date_time** | **datetime** | | [optional]
**uuid** | **str** | | [optional] **uuid** | **str** | | [optional]

View File

@@ -3,9 +3,9 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**map_map_of_string** | **dict(str, dict(str, str))** | | [optional] **map_map_of_string** | **{str: ({str: (str,)},)}** | | [optional]
**map_of_enum_string** | **dict(str, str)** | | [optional] **map_of_enum_string** | **{str: (str,)}** | | [optional]
**direct_map** | **dict(str, bool)** | | [optional] **direct_map** | **{str: (bool,)}** | | [optional]
**indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] **indirect_map** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -5,7 +5,7 @@ Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**uuid** | **str** | | [optional] **uuid** | **str** | | [optional]
**date_time** | **datetime** | | [optional] **date_time** | **datetime** | | [optional]
**map** | [**dict(str, Animal)**](Animal.md) | | [optional] **map** | [**{str: (Animal,)}**](Animal.md) | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -4,10 +4,10 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**name** | **str** | | **name** | **str** | |
**photo_urls** | **list[str]** | | **photo_urls** | **[str]** | |
**id** | **int** | | [optional] **id** | **int** | | [optional]
**category** | [**Category**](Category.md) | | [optional] **category** | [**Category**](Category.md) | | [optional]
**tags** | [**list[Tag]**](Tag.md) | | [optional] **tags** | [**[Tag]**](Tag.md) | | [optional]
**status** | **str** | pet status in the store | [optional] **status** | **str** | pet status in the store | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -134,7 +134,7 @@ void (empty response body)
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **find_pets_by_status** # **find_pets_by_status**
> list[Pet] find_pets_by_status(status) > [Pet] find_pets_by_status(status)
Finds Pets by status Finds Pets by status
@@ -157,7 +157,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN'
configuration.host = "http://petstore.swagger.io:80/v2" configuration.host = "http://petstore.swagger.io:80/v2"
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration))
status = ['status_example'] # list[str] | Status values that need to be considered for filter status = ['status_example'] # [str] | Status values that need to be considered for filter
try: try:
# Finds Pets by status # Finds Pets by status
@@ -171,11 +171,11 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**status** | [**list[str]**](str.md)| Status values that need to be considered for filter | **status** | [**[str]**](str.md)| Status values that need to be considered for filter |
### Return type ### Return type
[**list[Pet]**](Pet.md) [**[Pet]**](Pet.md)
### Authorization ### Authorization
@@ -195,7 +195,7 @@ Name | Type | Description | Notes
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **find_pets_by_tags** # **find_pets_by_tags**
> list[Pet] find_pets_by_tags(tags) > [Pet] find_pets_by_tags(tags)
Finds Pets by tags Finds Pets by tags
@@ -218,7 +218,7 @@ configuration.access_token = 'YOUR_ACCESS_TOKEN'
configuration.host = "http://petstore.swagger.io:80/v2" configuration.host = "http://petstore.swagger.io:80/v2"
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration))
tags = ['tags_example'] # list[str] | Tags to filter by tags = ['tags_example'] # [str] | Tags to filter by
try: try:
# Finds Pets by tags # Finds Pets by tags
@@ -232,11 +232,11 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**tags** | [**list[str]**](str.md)| Tags to filter by | **tags** | [**[str]**](str.md)| Tags to filter by |
### Return type ### Return type
[**list[Pet]**](Pet.md) [**[Pet]**](Pet.md)
### Authorization ### Authorization
@@ -464,11 +464,12 @@ configuration.host = "http://petstore.swagger.io:80/v2"
api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration))
pet_id = 56 # int | ID of pet to update pet_id = 56 # int | ID of pet to update
additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional)
file = '/path/to/file' # file | file to upload (optional) file = open('/path/to/file', 'rb') # file_type | file to upload (optional)
files = open('/path/to/file', 'rb') # [file_type] | files to upload (optional)
try: try:
# uploads an image # uploads an image
api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file) api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file, files=files)
pprint(api_response) pprint(api_response)
except ApiException as e: except ApiException as e:
print("Exception when calling PetApi->upload_file: %s\n" % e) print("Exception when calling PetApi->upload_file: %s\n" % e)
@@ -480,7 +481,8 @@ Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**pet_id** | **int**| ID of pet to update | **pet_id** | **int**| ID of pet to update |
**additional_metadata** | **str**| Additional data to pass to server | [optional] **additional_metadata** | **str**| Additional data to pass to server | [optional]
**file** | **file**| file to upload | [optional] **file** | **file_type**| file to upload | [optional]
**files** | [**[file_type]**](file_type.md)| files to upload | [optional]
### Return type ### Return type
@@ -525,7 +527,7 @@ configuration.host = "http://petstore.swagger.io:80/v2"
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration)) api_instance = petstore_api.PetApi(petstore_api.ApiClient(configuration))
pet_id = 56 # int | ID of pet to update pet_id = 56 # int | ID of pet to update
required_file = '/path/to/file' # file | file to upload required_file = open('/path/to/file', 'rb') # file_type | file to upload
additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional) additional_metadata = 'additional_metadata_example' # str | Additional data to pass to server (optional)
try: try:
@@ -541,7 +543,7 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**pet_id** | **int**| ID of pet to update | **pet_id** | **int**| ID of pet to update |
**required_file** | **file**| file to upload | **required_file** | **file_type**| file to upload |
**additional_metadata** | **str**| Additional data to pass to server | [optional] **additional_metadata** | **str**| Additional data to pass to server | [optional]
### Return type ### Return type

View File

@@ -65,7 +65,7 @@ No authorization required
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **get_inventory** # **get_inventory**
> dict(str, int) get_inventory() > {str: (int,)} get_inventory()
Returns pet inventories by status Returns pet inventories by status
@@ -104,7 +104,7 @@ This endpoint does not need any parameter.
### Return type ### Return type
**dict(str, int)** **{str: (int,)}**
### Authorization ### Authorization

View File

@@ -3,6 +3,7 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**any string name** | **bool** | any string name can be used but the value must be the correct type | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -3,7 +3,7 @@
## Properties ## Properties
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**array_item** | **list[int]** | | **array_item** | **[int]** | |
**string_item** | **str** | | defaults to 'what' **string_item** | **str** | | defaults to 'what'
**number_item** | **float** | | defaults to 1.234 **number_item** | **float** | | defaults to 1.234
**integer_item** | **int** | | defaults to -2 **integer_item** | **int** | | defaults to -2

View File

@@ -4,7 +4,7 @@
Name | Type | Description | Notes Name | Type | Description | Notes
------------ | ------------- | ------------- | ------------- ------------ | ------------- | ------------- | -------------
**bool_item** | **bool** | | **bool_item** | **bool** | |
**array_item** | **list[int]** | | **array_item** | **[int]** | |
**string_item** | **str** | | defaults to 'what' **string_item** | **str** | | defaults to 'what'
**number_item** | **float** | | defaults to 1.234 **number_item** | **float** | | defaults to 1.234
**integer_item** | **int** | | defaults to -2 **integer_item** | **int** | | defaults to -2

View File

@@ -83,7 +83,7 @@ from pprint import pprint
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.UserApi() api_instance = petstore_api.UserApi()
body = [petstore_api.User()] # list[User] | List of user object body = [petstore_api.User()] # [User] | List of user object
try: try:
# Creates list of users with given input array # Creates list of users with given input array
@@ -96,7 +96,7 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**body** | [**list[User]**](User.md)| List of user object | **body** | [**[User]**](User.md)| List of user object |
### Return type ### Return type
@@ -134,7 +134,7 @@ from pprint import pprint
# Create an instance of the API class # Create an instance of the API class
api_instance = petstore_api.UserApi() api_instance = petstore_api.UserApi()
body = [petstore_api.User()] # list[User] | List of user object body = [petstore_api.User()] # [User] | List of user object
try: try:
# Creates list of users with given input array # Creates list of users with given input array
@@ -147,7 +147,7 @@ except ApiException as e:
Name | Type | Description | Notes Name | Type | Description | Notes
------------- | ------------- | ------------- | ------------- ------------- | ------------- | ------------- | -------------
**body** | [**list[User]**](User.md)| List of user object | **body** | [**[User]**](User.md)| List of user object |
### Return type ### Return type

View File

@@ -7,31 +7,31 @@ Name | Type | Description | Notes
**attribute_number** | **float** | | [optional] **attribute_number** | **float** | | [optional]
**attribute_integer** | **int** | | [optional] **attribute_integer** | **int** | | [optional]
**attribute_boolean** | **bool** | | [optional] **attribute_boolean** | **bool** | | [optional]
**wrapped_array** | **list[int]** | | [optional] **wrapped_array** | **[int]** | | [optional]
**name_string** | **str** | | [optional] **name_string** | **str** | | [optional]
**name_number** | **float** | | [optional] **name_number** | **float** | | [optional]
**name_integer** | **int** | | [optional] **name_integer** | **int** | | [optional]
**name_boolean** | **bool** | | [optional] **name_boolean** | **bool** | | [optional]
**name_array** | **list[int]** | | [optional] **name_array** | **[int]** | | [optional]
**name_wrapped_array** | **list[int]** | | [optional] **name_wrapped_array** | **[int]** | | [optional]
**prefix_string** | **str** | | [optional] **prefix_string** | **str** | | [optional]
**prefix_number** | **float** | | [optional] **prefix_number** | **float** | | [optional]
**prefix_integer** | **int** | | [optional] **prefix_integer** | **int** | | [optional]
**prefix_boolean** | **bool** | | [optional] **prefix_boolean** | **bool** | | [optional]
**prefix_array** | **list[int]** | | [optional] **prefix_array** | **[int]** | | [optional]
**prefix_wrapped_array** | **list[int]** | | [optional] **prefix_wrapped_array** | **[int]** | | [optional]
**namespace_string** | **str** | | [optional] **namespace_string** | **str** | | [optional]
**namespace_number** | **float** | | [optional] **namespace_number** | **float** | | [optional]
**namespace_integer** | **int** | | [optional] **namespace_integer** | **int** | | [optional]
**namespace_boolean** | **bool** | | [optional] **namespace_boolean** | **bool** | | [optional]
**namespace_array** | **list[int]** | | [optional] **namespace_array** | **[int]** | | [optional]
**namespace_wrapped_array** | **list[int]** | | [optional] **namespace_wrapped_array** | **[int]** | | [optional]
**prefix_ns_string** | **str** | | [optional] **prefix_ns_string** | **str** | | [optional]
**prefix_ns_number** | **float** | | [optional] **prefix_ns_number** | **float** | | [optional]
**prefix_ns_integer** | **int** | | [optional] **prefix_ns_integer** | **int** | | [optional]
**prefix_ns_boolean** | **bool** | | [optional] **prefix_ns_boolean** | **bool** | | [optional]
**prefix_ns_array** | **list[int]** | | [optional] **prefix_ns_array** | **[int]** | | [optional]
**prefix_ns_wrapped_array** | **list[int]** | | [optional] **prefix_ns_wrapped_array** | **[int]** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -22,10 +22,18 @@ from petstore_api.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from petstore_api.model_utils import ( from petstore_api.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
from petstore_api.models.client import Client
class AnotherFakeApi(object): class AnotherFakeApi(object):
@@ -50,28 +58,55 @@ class AnotherFakeApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param Client body: client model (required) :param Client body: client model (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: Client :return: Client
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.call_123_test_special_tags = Endpoint( self.call_123_test_special_tags = Endpoint(
settings={ settings={
'response_type': 'Client', 'response_type': (Client,),
'auth': [], 'auth': [],
'endpoint_path': '/another-fake/dummy', 'endpoint_path': '/another-fake/dummy',
'operation_id': 'call_123_test_special_tags', 'operation_id': 'call_123_test_special_tags',
@@ -98,7 +133,7 @@ class AnotherFakeApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'Client', 'body': (Client,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -128,7 +163,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -164,11 +199,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -182,8 +230,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -194,6 +241,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -207,14 +268,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -239,20 +306,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -261,7 +323,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -300,9 +366,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -22,10 +22,18 @@ from petstore_api.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from petstore_api.model_utils import ( from petstore_api.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
from petstore_api.models.client import Client
class FakeClassnameTags123Api(object): class FakeClassnameTags123Api(object):
@@ -50,28 +58,55 @@ class FakeClassnameTags123Api(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param Client body: client model (required) :param Client body: client model (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: Client :return: Client
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.test_classname = Endpoint( self.test_classname = Endpoint(
settings={ settings={
'response_type': 'Client', 'response_type': (Client,),
'auth': [ 'auth': [
'api_key_query' 'api_key_query'
], ],
@@ -100,7 +135,7 @@ class FakeClassnameTags123Api(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'Client', 'body': (Client,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -130,7 +165,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -166,11 +201,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -184,8 +232,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -196,6 +243,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -209,14 +270,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -241,20 +308,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -263,7 +325,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -302,9 +368,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -22,10 +22,19 @@ from petstore_api.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from petstore_api.model_utils import ( from petstore_api.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
from petstore_api.models.api_response import ApiResponse
from petstore_api.models.pet import Pet
class PetApi(object): class PetApi(object):
@@ -49,22 +58,49 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param Pet body: Pet object that needs to be added to the store (required) :param Pet body: Pet object that needs to be added to the store (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -99,7 +135,7 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'Pet', 'body': (Pet,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -129,23 +165,50 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int pet_id: Pet id to delete (required) :param int pet_id: Pet id to delete (required)
:param str api_key: :param str api_key:
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['pet_id'] = pet_id kwargs['pet_id'] = pet_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -181,8 +244,8 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'pet_id': 'int', 'pet_id': (int,),
'api_key': 'str', 'api_key': (str,),
}, },
'attribute_map': { 'attribute_map': {
'pet_id': 'petId', 'pet_id': 'petId',
@@ -213,28 +276,55 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param list[str] status: Status values that need to be considered for filter (required) Default is False.
:param [str] status: Status values that need to be considered for filter (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
:return: list[Pet] Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: [Pet]
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['status'] = status kwargs['status'] = status
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.find_pets_by_status = Endpoint( self.find_pets_by_status = Endpoint(
settings={ settings={
'response_type': 'list[Pet]', 'response_type': ([Pet],),
'auth': [ 'auth': [
'petstore_auth' 'petstore_auth'
], ],
@@ -270,7 +360,7 @@ class PetApi(object):
}, },
}, },
'openapi_types': { 'openapi_types': {
'status': 'list[str]', 'status': ([str],),
}, },
'attribute_map': { 'attribute_map': {
'status': 'status', 'status': 'status',
@@ -303,28 +393,55 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param list[str] tags: Tags to filter by (required) Default is False.
:param [str] tags: Tags to filter by (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
:return: list[Pet] Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: [Pet]
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['tags'] = tags kwargs['tags'] = tags
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.find_pets_by_tags = Endpoint( self.find_pets_by_tags = Endpoint(
settings={ settings={
'response_type': 'list[Pet]', 'response_type': ([Pet],),
'auth': [ 'auth': [
'petstore_auth' 'petstore_auth'
], ],
@@ -353,7 +470,7 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'tags': 'list[str]', 'tags': ([str],),
}, },
'attribute_map': { 'attribute_map': {
'tags': 'tags', 'tags': 'tags',
@@ -386,28 +503,55 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int pet_id: ID of pet to return (required) :param int pet_id: ID of pet to return (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: Pet :return: Pet
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['pet_id'] = pet_id kwargs['pet_id'] = pet_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.get_pet_by_id = Endpoint( self.get_pet_by_id = Endpoint(
settings={ settings={
'response_type': 'Pet', 'response_type': (Pet,),
'auth': [ 'auth': [
'api_key' 'api_key'
], ],
@@ -436,7 +580,7 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'pet_id': 'int', 'pet_id': (int,),
}, },
'attribute_map': { 'attribute_map': {
'pet_id': 'petId', 'pet_id': 'petId',
@@ -467,22 +611,49 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param Pet body: Pet object that needs to be added to the store (required) :param Pet body: Pet object that needs to be added to the store (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -517,7 +688,7 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'Pet', 'body': (Pet,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -547,24 +718,51 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int pet_id: ID of pet that needs to be updated (required) :param int pet_id: ID of pet that needs to be updated (required)
:param str name: Updated name of the pet :param str name: Updated name of the pet
:param str status: Updated status of the pet :param str status: Updated status of the pet
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['pet_id'] = pet_id kwargs['pet_id'] = pet_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -601,9 +799,9 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'pet_id': 'int', 'pet_id': (int,),
'name': 'str', 'name': (str,),
'status': 'str', 'status': (str,),
}, },
'attribute_map': { 'attribute_map': {
'pet_id': 'petId', 'pet_id': 'petId',
@@ -637,30 +835,58 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int pet_id: ID of pet to update (required) :param int pet_id: ID of pet to update (required)
:param str additional_metadata: Additional data to pass to server :param str additional_metadata: Additional data to pass to server
:param file file: file to upload :param file_type file: file to upload
:param [file_type] files: files to upload
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: ApiResponse :return: ApiResponse
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['pet_id'] = pet_id kwargs['pet_id'] = pet_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.upload_file = Endpoint( self.upload_file = Endpoint(
settings={ settings={
'response_type': 'ApiResponse', 'response_type': (ApiResponse,),
'auth': [ 'auth': [
'petstore_auth' 'petstore_auth'
], ],
@@ -674,6 +900,7 @@ class PetApi(object):
'pet_id', 'pet_id',
'additional_metadata', 'additional_metadata',
'file', 'file',
'files',
], ],
'required': [ 'required': [
'pet_id', 'pet_id',
@@ -691,21 +918,25 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'pet_id': 'int', 'pet_id': (int,),
'additional_metadata': 'str', 'additional_metadata': (str,),
'file': 'file', 'file': (file_type,),
'files': ([file_type],),
}, },
'attribute_map': { 'attribute_map': {
'pet_id': 'petId', 'pet_id': 'petId',
'additional_metadata': 'additionalMetadata', 'additional_metadata': 'additionalMetadata',
'file': 'file', 'file': 'file',
'files': 'files',
}, },
'location_map': { 'location_map': {
'pet_id': 'path', 'pet_id': 'path',
'additional_metadata': 'form', 'additional_metadata': 'form',
'file': 'form', 'file': 'form',
'files': 'form',
}, },
'collection_format_map': { 'collection_format_map': {
'files': 'csv',
} }
}, },
headers_map={ headers_map={
@@ -729,31 +960,58 @@ class PetApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int pet_id: ID of pet to update (required) :param int pet_id: ID of pet to update (required)
:param file required_file: file to upload (required) :param file_type required_file: file to upload (required)
:param str additional_metadata: Additional data to pass to server :param str additional_metadata: Additional data to pass to server
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: ApiResponse :return: ApiResponse
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['pet_id'] = pet_id kwargs['pet_id'] = pet_id
kwargs['required_file'] = required_file kwargs['required_file'] = required_file
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.upload_file_with_required_file = Endpoint( self.upload_file_with_required_file = Endpoint(
settings={ settings={
'response_type': 'ApiResponse', 'response_type': (ApiResponse,),
'auth': [ 'auth': [
'petstore_auth' 'petstore_auth'
], ],
@@ -785,9 +1043,9 @@ class PetApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'pet_id': 'int', 'pet_id': (int,),
'required_file': 'file', 'required_file': (file_type,),
'additional_metadata': 'str', 'additional_metadata': (str,),
}, },
'attribute_map': { 'attribute_map': {
'pet_id': 'petId', 'pet_id': 'petId',
@@ -822,7 +1080,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -858,11 +1116,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -876,8 +1147,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -888,6 +1158,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -901,14 +1185,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -933,20 +1223,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -955,7 +1240,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -994,9 +1283,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -22,10 +22,18 @@ from petstore_api.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from petstore_api.model_utils import ( from petstore_api.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
from petstore_api.models.order import Order
class StoreApi(object): class StoreApi(object):
@@ -50,22 +58,49 @@ class StoreApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param str order_id: ID of the order that needs to be deleted (required) :param str order_id: ID of the order that needs to be deleted (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['order_id'] = order_id kwargs['order_id'] = order_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -98,7 +133,7 @@ class StoreApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'order_id': 'str', 'order_id': (str,),
}, },
'attribute_map': { 'attribute_map': {
'order_id': 'order_id', 'order_id': 'order_id',
@@ -127,26 +162,53 @@ class StoreApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
:return: dict(str, int) Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: {str: (int,)}
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.get_inventory = Endpoint( self.get_inventory = Endpoint(
settings={ settings={
'response_type': 'dict(str, int)', 'response_type': ({str: (int,)},),
'auth': [ 'auth': [
'api_key' 'api_key'
], ],
@@ -200,28 +262,55 @@ class StoreApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param int order_id: ID of pet that needs to be fetched (required) :param int order_id: ID of pet that needs to be fetched (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: Order :return: Order
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['order_id'] = order_id kwargs['order_id'] = order_id
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.get_order_by_id = Endpoint( self.get_order_by_id = Endpoint(
settings={ settings={
'response_type': 'Order', 'response_type': (Order,),
'auth': [], 'auth': [],
'endpoint_path': '/store/order/{order_id}', 'endpoint_path': '/store/order/{order_id}',
'operation_id': 'get_order_by_id', 'operation_id': 'get_order_by_id',
@@ -254,7 +343,7 @@ class StoreApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'order_id': 'int', 'order_id': (int,),
}, },
'attribute_map': { 'attribute_map': {
'order_id': 'order_id', 'order_id': 'order_id',
@@ -285,28 +374,55 @@ class StoreApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param Order body: order placed for purchasing the pet (required) :param Order body: order placed for purchasing the pet (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: Order :return: Order
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.place_order = Endpoint( self.place_order = Endpoint(
settings={ settings={
'response_type': 'Order', 'response_type': (Order,),
'auth': [], 'auth': [],
'endpoint_path': '/store/order', 'endpoint_path': '/store/order',
'operation_id': 'place_order', 'operation_id': 'place_order',
@@ -333,7 +449,7 @@ class StoreApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'Order', 'body': (Order,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -362,7 +478,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -398,11 +514,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -416,8 +545,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -428,6 +556,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -441,14 +583,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -473,20 +621,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -495,7 +638,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -534,9 +681,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -22,10 +22,18 @@ from petstore_api.exceptions import (
ApiTypeError, ApiTypeError,
ApiValueError ApiValueError
) )
from petstore_api.model_utils import ( from petstore_api.model_utils import ( # noqa: F401
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
int,
none_type,
str,
validate_and_convert_types
) )
from petstore_api.models.user import User
class UserApi(object): class UserApi(object):
@@ -50,22 +58,49 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param User body: Created user object (required) :param User body: Created user object (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -98,7 +133,7 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'User', 'body': (User,),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -125,22 +160,49 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param list[User] body: List of user object (required) Default is False.
:param [User] body: List of user object (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -173,7 +235,7 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'list[User]', 'body': ([User],),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -200,22 +262,49 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param list[User] body: List of user object (required) Default is False.
:param [User] body: List of user object (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -248,7 +337,7 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'body': 'list[User]', 'body': ([User],),
}, },
'attribute_map': { 'attribute_map': {
}, },
@@ -276,22 +365,49 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param str username: The name that needs to be deleted (required) :param str username: The name that needs to be deleted (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['username'] = username kwargs['username'] = username
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -324,7 +440,7 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'username': 'str', 'username': (str,),
}, },
'attribute_map': { 'attribute_map': {
'username': 'username', 'username': 'username',
@@ -352,28 +468,55 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param str username: The name that needs to be fetched. Use user1 for testing. (required) :param str username: The name that needs to be fetched. Use user1 for testing. (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: User :return: User
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['username'] = username kwargs['username'] = username
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.get_user_by_name = Endpoint( self.get_user_by_name = Endpoint(
settings={ settings={
'response_type': 'User', 'response_type': (User,),
'auth': [], 'auth': [],
'endpoint_path': '/user/{username}', 'endpoint_path': '/user/{username}',
'operation_id': 'get_user_by_name', 'operation_id': 'get_user_by_name',
@@ -400,7 +543,7 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'username': 'str', 'username': (str,),
}, },
'attribute_map': { 'attribute_map': {
'username': 'username', 'username': 'username',
@@ -431,30 +574,57 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param str username: The user name for login (required) :param str username: The user name for login (required)
:param str password: The password for login in clear text (required) :param str password: The password for login in clear text (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: str :return: str
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['username'] = username kwargs['username'] = username
kwargs['password'] = password kwargs['password'] = password
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.login_user = Endpoint( self.login_user = Endpoint(
settings={ settings={
'response_type': 'str', 'response_type': (str,),
'auth': [], 'auth': [],
'endpoint_path': '/user/login', 'endpoint_path': '/user/login',
'operation_id': 'login_user', 'operation_id': 'login_user',
@@ -483,8 +653,8 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'username': 'str', 'username': (str,),
'password': 'str', 'password': (str,),
}, },
'attribute_map': { 'attribute_map': {
'username': 'username', 'username': 'username',
@@ -517,21 +687,48 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
self.logout_user = Endpoint( self.logout_user = Endpoint(
@@ -586,23 +783,50 @@ class UserApi(object):
>>> result = thread.get() >>> result = thread.get()
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
Default is False.
:param str username: name that need to be deleted (required) :param str username: name that need to be deleted (required)
:param User body: Updated user object (required) :param User body: Updated user object (required)
:param _return_http_data_only: response data without head status :param _return_http_data_only: response data without head status
code and headers code and headers. Default is True.
:param _preload_content: if False, the urllib3.HTTPResponse object :param _preload_content: if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data. will be returned without reading/decoding response data.
Default is True. Default is True.
:param _request_timeout: timeout setting for this request. If one :param _request_timeout: timeout setting for this request. If one
number provided, it will be total request timeout. It can also number provided, it will be total request timeout. It can also
be a pair (tuple) of (connection, read) timeouts. be a pair (tuple) of (connection, read) timeouts.
Default is None.
:param _check_input_type: boolean specifying if type checking
should be done one the data sent to the server.
Default is True.
:param _check_return_type: boolean specifying if type checking
should be done one the data received from the server.
Default is True.
:param _host_index: integer specifying the index of the server
that we want to use.
Default is 0.
:return: None :return: None
If the method is called asynchronously, returns the request If the method is called asynchronously, returns the request
thread. thread.
""" """
kwargs['async_req'] = kwargs.get(
'async_req', False
)
kwargs['_return_http_data_only'] = kwargs.get( kwargs['_return_http_data_only'] = kwargs.get(
'_return_http_data_only', True '_return_http_data_only', True
) )
kwargs['_preload_content'] = kwargs.get(
'_preload_content', True
)
kwargs['_request_timeout'] = kwargs.get(
'_request_timeout', None
)
kwargs['_check_input_type'] = kwargs.get(
'_check_input_type', True
)
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['username'] = username kwargs['username'] = username
kwargs['body'] = body kwargs['body'] = body
return self.call_with_http_info(**kwargs) return self.call_with_http_info(**kwargs)
@@ -638,8 +862,8 @@ class UserApi(object):
'allowed_values': { 'allowed_values': {
}, },
'openapi_types': { 'openapi_types': {
'username': 'str', 'username': (str,),
'body': 'User', 'body': (User,),
}, },
'attribute_map': { 'attribute_map': {
'username': 'username', 'username': 'username',
@@ -667,7 +891,7 @@ class Endpoint(object):
Args: Args:
settings (dict): see below key value pairs settings (dict): see below key value pairs
'response_type' (str): response type 'response_type' (tuple/None): response type
'auth' (list): a list of auth type keys 'auth' (list): a list of auth type keys
'endpoint_path' (str): the endpoint path 'endpoint_path' (str): the endpoint path
'operation_id' (str): endpoint string identifier 'operation_id' (str): endpoint string identifier
@@ -703,11 +927,24 @@ class Endpoint(object):
'_host_index', '_host_index',
'_preload_content', '_preload_content',
'_request_timeout', '_request_timeout',
'_return_http_data_only' '_return_http_data_only',
'_check_input_type',
'_check_return_type'
]) ])
self.params_map['nullable'].extend(['_request_timeout'])
self.validations = root_map['validations'] self.validations = root_map['validations']
self.allowed_values = root_map['allowed_values'] self.allowed_values = root_map['allowed_values']
self.openapi_types = root_map['openapi_types'] self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
'_check_input_type': (bool,),
'_check_return_type': (bool,)
}
self.openapi_types.update(extra_types)
self.attribute_map = root_map['attribute_map'] self.attribute_map = root_map['attribute_map']
self.location_map = root_map['location_map'] self.location_map = root_map['location_map']
self.collection_format_map = root_map['collection_format_map'] self.collection_format_map = root_map['collection_format_map']
@@ -721,8 +958,7 @@ class Endpoint(object):
check_allowed_values( check_allowed_values(
self.allowed_values, self.allowed_values,
(param,), (param,),
kwargs[param], kwargs[param]
self.validations
) )
for param in self.params_map['validation']: for param in self.params_map['validation']:
@@ -733,6 +969,20 @@ class Endpoint(object):
kwargs[param] kwargs[param]
) )
if kwargs['_check_input_type'] is False:
return
for key, value in six.iteritems(kwargs):
fixed_val = validate_and_convert_types(
value,
self.openapi_types[key],
[key],
False,
kwargs['_check_input_type'],
configuration=self.api_client.configuration
)
kwargs[key] = fixed_val
def __gather_params(self, kwargs): def __gather_params(self, kwargs):
params = { params = {
'body': None, 'body': None,
@@ -746,14 +996,20 @@ class Endpoint(object):
for param_name, param_value in six.iteritems(kwargs): for param_name, param_value in six.iteritems(kwargs):
param_location = self.location_map.get(param_name) param_location = self.location_map.get(param_name)
if param_location is None:
continue
if param_location: if param_location:
if param_location == 'body': if param_location == 'body':
params['body'] = param_value params['body'] = param_value
continue continue
base_name = self.attribute_map[param_name] base_name = self.attribute_map[param_name]
if (param_location == 'form' and if (param_location == 'form' and
self.openapi_types[param_name] == 'file'): self.openapi_types[param_name] == (file_type,)):
param_location = 'file' params['file'][param_name] = [param_value]
elif (param_location == 'form' and
self.openapi_types[param_name] == ([file_type],)):
# param_value is already a list
params['file'][param_name] = param_value
elif param_location in {'form', 'query'}: elif param_location in {'form', 'query'}:
param_value_full = (base_name, param_value) param_value_full = (base_name, param_value)
params[param_location].append(param_value_full) params[param_location].append(param_value_full)
@@ -778,20 +1034,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs): def call_with_http_info(self, **kwargs):
if kwargs.get('_host_index') and self.settings['servers']: try:
_host_index = kwargs.get('_host_index') _host = self.settings['servers'][kwargs['_host_index']]
try: except IndexError:
_host = self.settings['servers'][_host_index] if self.settings['servers']:
except IndexError:
raise ApiValueError( raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s" % "Invalid host index. Must be 0 <= index < %s" %
len(self.settings['servers']) len(self.settings['servers'])
) )
else: _host = None
try:
_host = self.settings['servers'][0]
except IndexError:
_host = None
for key, value in six.iteritems(kwargs): for key, value in six.iteritems(kwargs):
if key not in self.params_map['all']: if key not in self.params_map['all']:
@@ -800,7 +1051,11 @@ class Endpoint(object):
" to method `%s`" % " to method `%s`" %
(key, self.settings['operation_id']) (key, self.settings['operation_id'])
) )
if key not in self.params_map['nullable'] and value is None: # only throw this nullable ApiValueError if _check_input_type
# is False, if _check_input_type==True we catch this case
# in self.__validate_inputs
if (key not in self.params_map['nullable'] and value is None
and kwargs['_check_input_type'] is False):
raise ApiValueError( raise ApiValueError(
"Value may not be None for non-nullable parameter `%s`" "Value may not be None for non-nullable parameter `%s`"
" when calling `%s`" % " when calling `%s`" %
@@ -839,9 +1094,10 @@ class Endpoint(object):
files=params['file'], files=params['file'],
response_type=self.settings['response_type'], response_type=self.settings['response_type'],
auth_settings=self.settings['auth'], auth_settings=self.settings['auth'],
async_req=kwargs.get('async_req'), async_req=kwargs['async_req'],
_return_http_data_only=kwargs.get('_return_http_data_only'), _check_type=kwargs['_check_return_type'],
_preload_content=kwargs.get('_preload_content', True), _return_http_data_only=kwargs['_return_http_data_only'],
_request_timeout=kwargs.get('_request_timeout'), _preload_content=kwargs['_preload_content'],
_request_timeout=kwargs['_request_timeout'],
_host=_host, _host=_host,
collection_formats=params['collection_format']) collection_formats=params['collection_format'])

View File

@@ -10,27 +10,29 @@
from __future__ import absolute_import from __future__ import absolute_import
import datetime
import inspect
import json import json
import mimetypes import mimetypes
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
import os import os
import re
import tempfile
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
import six import six
from six.moves.urllib.parse import quote from six.moves.urllib.parse import quote
import petstore_api.models
from petstore_api import rest from petstore_api import rest
from petstore_api.configuration import Configuration from petstore_api.configuration import Configuration
from petstore_api.exceptions import ApiValueError
from petstore_api.model_utils import ( from petstore_api.model_utils import (
ModelNormal, ModelNormal,
ModelSimple ModelSimple,
date,
datetime,
deserialize_file,
file_type,
model_to_dict,
str,
validate_and_convert_types
) )
from petstore_api.exceptions import ApiValueError
class ApiClient(object): class ApiClient(object):
@@ -55,17 +57,11 @@ class ApiClient(object):
to the API. More threads means more concurrent API requests. to the API. More threads means more concurrent API requests.
""" """
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types # six.binary_type python2=str, python3=bytes
NATIVE_TYPES_MAPPING = { # six.text_type python2=unicode, python3=str
'int': int, PRIMITIVE_TYPES = (
'long': int if six.PY3 else long, # noqa: F821 (float, bool, six.binary_type, six.text_type) + six.integer_types
'float': float, )
'str': str,
'bool': bool,
'date': datetime.date,
'datetime': datetime.datetime,
'object': object,
}
_pool = None _pool = None
def __init__(self, configuration=None, header_name=None, header_value=None, def __init__(self, configuration=None, header_name=None, header_value=None,
@@ -115,7 +111,8 @@ class ApiClient(object):
query_params=None, header_params=None, body=None, post_params=None, query_params=None, header_params=None, body=None, post_params=None,
files=None, response_type=None, auth_settings=None, files=None, response_type=None, auth_settings=None,
_return_http_data_only=None, collection_formats=None, _return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None, _host=None): _preload_content=True, _request_timeout=None, _host=None,
_check_type=None):
config = self.configuration config = self.configuration
@@ -182,7 +179,11 @@ class ApiClient(object):
if _preload_content: if _preload_content:
# deserialize response data # deserialize response data
if response_type: if response_type:
return_data = self.deserialize(response_data, response_type) return_data = self.deserialize(
response_data,
response_type,
_check_type
)
else: else:
return_data = None return_data = None
@@ -216,93 +217,73 @@ class ApiClient(object):
elif isinstance(obj, tuple): elif isinstance(obj, tuple):
return tuple(self.sanitize_for_serialization(sub_obj) return tuple(self.sanitize_for_serialization(sub_obj)
for sub_obj in obj) for sub_obj in obj)
elif isinstance(obj, (datetime.datetime, datetime.date)): elif isinstance(obj, (datetime, date)):
return obj.isoformat() return obj.isoformat()
if isinstance(obj, dict): if isinstance(obj, dict):
obj_dict = obj obj_dict = obj
elif isinstance(obj, ModelNormal): elif isinstance(obj, ModelNormal):
# Convert model obj to dict except # Convert model obj to dict
# attributes `openapi_types`, `attribute_map`
# and attributes which value is not None.
# Convert attribute name to json key in # Convert attribute name to json key in
# model definition for request. # model definition for request
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) obj_dict = model_to_dict(obj, serialize=True)
for attr, _ in six.iteritems(obj.openapi_types)
if getattr(obj, attr) is not None}
elif isinstance(obj, ModelSimple): elif isinstance(obj, ModelSimple):
return self.sanitize_for_serialization(obj.value) return self.sanitize_for_serialization(obj.value)
return {key: self.sanitize_for_serialization(val) return {key: self.sanitize_for_serialization(val)
for key, val in six.iteritems(obj_dict)} for key, val in six.iteritems(obj_dict)}
def deserialize(self, response, response_type): def deserialize(self, response, response_type, _check_type):
"""Deserializes response into an object. """Deserializes response into an object.
:param response: RESTResponse object to be deserialized. :param response: RESTResponse object to be deserialized.
:param response_type: class literal for :param response_type: For the response, a tuple containing:
deserialized object, or string of class name. valid classes
a list containing valid classes (for list schemas)
a dict containing a tuple of valid classes as the value
Example values:
(str,)
(Pet,)
(float, none_type)
([int, none_type],)
({str: (bool, str, int, float, date, datetime, str, none_type)},)
:param _check_type: boolean, whether to check the types of the data
received from the server
:return: deserialized object. :return: deserialized object.
""" """
# handle file downloading # handle file downloading
# save response body into a tmp file and return the instance # save response body into a tmp file and return the instance
if response_type == "file": if response_type == (file_type,):
return self.__deserialize_file(response) content_disposition = response.getheader("Content-Disposition")
return deserialize_file(response.data, self.configuration,
content_disposition=content_disposition)
# fetch data from response object # fetch data from response object
try: try:
data = json.loads(response.data) received_data = json.loads(response.data)
except ValueError: except ValueError:
data = response.data received_data = response.data
return self.__deserialize(data, response_type) # store our data under the key of 'received_data' so users have some
# context if they are deserializing a string and the data type is wrong
def __deserialize(self, data, klass): deserialized_data = validate_and_convert_types(
"""Deserializes dict, list, str into an object. received_data,
response_type,
:param data: dict, list or str. ['received_data'],
:param klass: class literal, or string of class name. True,
_check_type,
:return: object. configuration=self.configuration
""" )
if data is None: return deserialized_data
return None
if type(klass) == str:
if klass.startswith('list['):
sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
if klass.startswith('dict('):
sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2)
return {k: self.__deserialize(v, sub_kls)
for k, v in six.iteritems(data)}
# convert str to class
if klass in self.NATIVE_TYPES_MAPPING:
klass = self.NATIVE_TYPES_MAPPING[klass]
else:
klass = getattr(petstore_api.models, klass)
if klass in self.PRIMITIVE_TYPES:
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
elif klass == datetime.date:
return self.__deserialize_date(data)
elif klass == datetime.datetime:
return self.__deserialize_datatime(data)
else:
return self.__deserialize_model(data, klass)
def call_api(self, resource_path, method, def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None, path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None, body=None, post_params=None, files=None,
response_type=None, auth_settings=None, async_req=None, response_type=None, auth_settings=None, async_req=None,
_return_http_data_only=None, collection_formats=None, _return_http_data_only=None, collection_formats=None,
_preload_content=True, _request_timeout=None, _host=None): _preload_content=True, _request_timeout=None, _host=None,
_check_type=None):
"""Makes the HTTP request (synchronous) and returns deserialized data. """Makes the HTTP request (synchronous) and returns deserialized data.
To make an async_req request, set the async_req parameter. To make an async_req request, set the async_req parameter.
@@ -317,9 +298,18 @@ class ApiClient(object):
:param post_params dict: Request post form parameters, :param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`. for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request. :param auth_settings list: Auth Settings names for the request.
:param response: Response data type. :param response_type: For the response, a tuple containing:
:param files dict: key -> filename, value -> filepath, valid classes
for `multipart/form-data`. a list containing valid classes (for list schemas)
a dict containing a tuple of valid classes as the value
Example values:
(str,)
(Pet,)
(float, none_type)
([int, none_type],)
({str: (bool, str, int, float, date, datetime, str, none_type)},)
:param files dict: key -> field name, value -> a list of open file
objects for `multipart/form-data`.
:param async_req bool: execute request asynchronously :param async_req bool: execute request asynchronously
:param _return_http_data_only: response data without head status code :param _return_http_data_only: response data without head status code
and headers and headers
@@ -332,6 +322,8 @@ class ApiClient(object):
number provided, it will be total request number provided, it will be total request
timeout. It can also be a pair (tuple) of timeout. It can also be a pair (tuple) of
(connection, read) timeouts. (connection, read) timeouts.
:param _check_type: boolean describing if the data back from the server
should have its type checked.
:return: :return:
If async_req parameter is True, If async_req parameter is True,
the request will be called asynchronously. the request will be called asynchronously.
@@ -345,7 +337,8 @@ class ApiClient(object):
body, post_params, files, body, post_params, files,
response_type, auth_settings, response_type, auth_settings,
_return_http_data_only, collection_formats, _return_http_data_only, collection_formats,
_preload_content, _request_timeout, _host) _preload_content, _request_timeout, _host,
_check_type)
else: else:
thread = self.pool.apply_async(self.__call_api, (resource_path, thread = self.pool.apply_async(self.__call_api, (resource_path,
method, path_params, query_params, method, path_params, query_params,
@@ -356,7 +349,7 @@ class ApiClient(object):
collection_formats, collection_formats,
_preload_content, _preload_content,
_request_timeout, _request_timeout,
_host)) _host, _check_type))
return thread return thread
def request(self, method, url, query_params=None, headers=None, def request(self, method, url, query_params=None, headers=None,
@@ -453,24 +446,34 @@ class ApiClient(object):
def files_parameters(self, files=None): def files_parameters(self, files=None):
"""Builds form parameters. """Builds form parameters.
:param files: File parameters. :param files: None or a dict with key=param_name and
:return: Form parameters with files. value is a list of open file objects
:return: List of tuples of form parameters with file data
""" """
params = [] if files is None:
return []
if files: params = []
for k, v in six.iteritems(files): for param_name, file_instances in six.iteritems(files):
if not v: if file_instances is None:
# if the file field is nullable, skip None values
continue
for file_instance in file_instances:
if file_instance is None:
# if the file field is nullable, skip None values
continue continue
file_names = v if type(v) is list else [v] if file_instance.closed is True:
for n in file_names: raise ApiValueError(
with open(n, 'rb') as f: "Cannot read a closed file. The passed in file_type "
filename = os.path.basename(f.name) "for %s must be open." % param_name
filedata = f.read() )
mimetype = (mimetypes.guess_type(filename)[0] or filename = os.path.basename(file_instance.name)
'application/octet-stream') filedata = file_instance.read()
params.append( mimetype = (mimetypes.guess_type(filename)[0] or
tuple([k, tuple([filename, filedata, mimetype])])) 'application/octet-stream')
params.append(
tuple([param_name, tuple([filename, filedata, mimetype])]))
file_instance.close()
return params return params
@@ -531,133 +534,3 @@ class ApiClient(object):
raise ApiValueError( raise ApiValueError(
'Authentication token must be in `query` or `header`' 'Authentication token must be in `query` or `header`'
) )
def __deserialize_file(self, response):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
:param response: RESTResponse.
:return: file path.
"""
fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition")
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
f.write(response.data)
return path
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return six.text_type(data)
except TypeError:
return data
except ValueError as exc:
raise ApiValueError(str(exc))
def __deserialize_object(self, value):
"""Return an original value.
:return: object.
"""
return value
def __deserialize_date(self, string):
"""Deserializes string to date.
:param string: str.
:return: date.
"""
try:
from dateutil.parser import parse
return parse(string).date()
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason="Failed to parse `{0}` as date object".format(string)
)
def __deserialize_datatime(self, string):
"""Deserializes string to datetime.
The string should be in iso8601 datetime format.
:param string: str.
:return: datetime.
"""
try:
from dateutil.parser import parse
return parse(string)
except ImportError:
return string
except ValueError:
raise rest.ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(string)
)
)
def __deserialize_model(self, data, klass):
"""Deserializes list or dict to model.
:param data: dict, list.
:param klass: class literal, ModelSimple or ModelNormal
:return: model object.
"""
if issubclass(klass, ModelSimple):
value = self.__deserialize(data, klass.openapi_types['value'])
return klass(value)
# code to handle ModelNormal
used_data = data
if not isinstance(data, (list, dict)):
used_data = [data]
keyword_args = {}
positional_args = []
if klass.openapi_types is not None:
for attr, attr_type in six.iteritems(klass.openapi_types):
if (data is not None and
klass.attribute_map[attr] in used_data):
value = used_data[klass.attribute_map[attr]]
keyword_args[attr] = self.__deserialize(value, attr_type)
end_index = None
argspec = inspect.getargspec(getattr(klass, '__init__'))
if argspec.defaults:
end_index = -len(argspec.defaults)
required_positional_args = argspec.args[1:end_index]
for index, req_positional_arg in enumerate(required_positional_args):
if keyword_args and req_positional_arg in keyword_args:
positional_args.append(keyword_args[req_positional_arg])
del keyword_args[req_positional_arg]
elif (not keyword_args and index < len(used_data) and
isinstance(used_data, list)):
positional_args.append(used_data[index])
instance = klass(*positional_args, **keyword_args)
if hasattr(instance, 'get_real_child_model'):
klass_name = instance.get_real_child_model(data)
if klass_name:
instance = self.__deserialize(data, klass_name)
return instance

View File

@@ -9,13 +9,162 @@
Generated by: https://openapi-generator.tech Generated by: https://openapi-generator.tech
""" """
import copy
from datetime import date, datetime # noqa: F401
import inspect
import os
import re import re
import tempfile
from petstore_api.exceptions import ApiValueError from dateutil.parser import parse
import six
from petstore_api.exceptions import (
ApiKeyError,
ApiTypeError,
ApiValueError,
)
none_type = type(None)
if six.PY3:
import io
file_type = io.IOBase
# these are needed for when other modules import str and int from here
str = str
int = int
else:
file_type = file # noqa: F821
str_py2 = str
unicode_py2 = unicode # noqa: F821
long_py2 = long # noqa: F821
int_py2 = int
# this requires that the future library is installed
from builtins import int, str
def check_allowed_values(allowed_values, input_variable_path, input_values, class OpenApiModel(object):
validations): """The base class for all OpenAPIModels"""
class ModelSimple(OpenApiModel):
"""the parent class of models whose type != object in their
swagger/openapi"""
class ModelNormal(OpenApiModel):
"""the parent class of models whose type == object in their
swagger/openapi"""
COERCION_INDEX_BY_TYPE = {
ModelNormal: 0,
ModelSimple: 1,
none_type: 2,
list: 3,
dict: 4,
float: 5,
int: 6,
bool: 7,
datetime: 8,
date: 9,
str: 10,
file_type: 11,
}
# these are used to limit what type conversions we try to do
# when we have a valid type already and we want to try converting
# to another type
UPCONVERSION_TYPE_PAIRS = (
(str, datetime),
(str, date),
(list, ModelNormal),
(dict, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
)
COERCIBLE_TYPE_PAIRS = {
False: ( # client instantiation of a model with client data
# (dict, ModelNormal),
# (list, ModelNormal),
# (str, ModelSimple),
# (int, ModelSimple),
# (float, ModelSimple),
# (list, ModelSimple),
# (str, int),
# (str, float),
# (str, datetime),
# (str, date),
# (int, str),
# (float, str),
),
True: ( # server -> client data
(dict, ModelNormal),
(list, ModelNormal),
(str, ModelSimple),
(int, ModelSimple),
(float, ModelSimple),
(list, ModelSimple),
# (str, int),
# (str, float),
(str, datetime),
(str, date),
# (int, str),
# (float, str),
(str, file_type)
),
}
def get_simple_class(input_value):
"""Returns an input_value's simple class that we will use for type checking
Python2:
float and int will return int, where int is the python3 int backport
str and unicode will return str, where str is the python3 str backport
Note: float and int ARE both instances of int backport
Note: str_py2 and unicode_py2 are NOT both instances of str backport
Args:
input_value (class/class_instance): the item for which we will return
the simple class
"""
if isinstance(input_value, type):
# input_value is a class
return input_value
elif isinstance(input_value, tuple):
return tuple
elif isinstance(input_value, list):
return list
elif isinstance(input_value, dict):
return dict
elif isinstance(input_value, none_type):
return none_type
elif isinstance(input_value, file_type):
return file_type
elif isinstance(input_value, bool):
# this must be higher than the int check because
# isinstance(True, int) == True
return bool
elif isinstance(input_value, int):
# for python2 input_value==long_instance -> return int
# where int is the python3 int backport
return int
elif isinstance(input_value, datetime):
# this must be higher than the date check because
# isinstance(datetime_instance, date) == True
return datetime
elif isinstance(input_value, date):
return date
elif (six.PY2 and isinstance(input_value, (str_py2, unicode_py2, str)) or
isinstance(input_value, str)):
return str
return type(input_value)
def check_allowed_values(allowed_values, input_variable_path, input_values):
"""Raises an exception if the input_values are not allowed """Raises an exception if the input_values are not allowed
Args: Args:
@@ -23,14 +172,9 @@ def check_allowed_values(allowed_values, input_variable_path, input_values,
input_variable_path (tuple): the path to the input variable input_variable_path (tuple): the path to the input variable
input_values (list/str/int/float/date/datetime): the values that we input_values (list/str/int/float/date/datetime): the values that we
are checking to see if they are in allowed_values are checking to see if they are in allowed_values
validations (dict): the validations dict
""" """
min_collection_length = (
validations.get(input_variable_path, {}).get('min_length') or
validations.get(input_variable_path, {}).get('min_items', 0))
these_allowed_values = list(allowed_values[input_variable_path].values()) these_allowed_values = list(allowed_values[input_variable_path].values())
if (isinstance(input_values, list) if (isinstance(input_values, list)
and len(input_values) > min_collection_length
and not set(input_values).issubset( and not set(input_values).issubset(
set(these_allowed_values))): set(these_allowed_values))):
invalid_values = ", ".join( invalid_values = ", ".join(
@@ -44,7 +188,6 @@ def check_allowed_values(allowed_values, input_variable_path, input_values,
) )
) )
elif (isinstance(input_values, dict) elif (isinstance(input_values, dict)
and len(input_values) > min_collection_length
and not set( and not set(
input_values.keys()).issubset(set(these_allowed_values))): input_values.keys()).issubset(set(these_allowed_values))):
invalid_values = ", ".join( invalid_values = ", ".join(
@@ -119,8 +262,21 @@ def check_validations(validations, input_variable_path, input_values):
) )
) )
items = ('exclusive_maximum', 'inclusive_maximum', 'exclusive_minimum',
'inclusive_minimum')
if (any(item in current_validations for item in items)):
if isinstance(input_values, list):
max_val = max(input_values)
min_val = min(input_values)
elif isinstance(input_values, dict):
max_val = max(input_values.values())
min_val = min(input_values.values())
else:
max_val = input_values
min_val = input_values
if ('exclusive_maximum' in current_validations and if ('exclusive_maximum' in current_validations and
input_values >= current_validations['exclusive_maximum']): max_val >= current_validations['exclusive_maximum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value less than `%s`" % ( "Invalid value for `%s`, must be a value less than `%s`" % (
input_variable_path[0], input_variable_path[0],
@@ -129,7 +285,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('inclusive_maximum' in current_validations and if ('inclusive_maximum' in current_validations and
input_values > current_validations['inclusive_maximum']): max_val > current_validations['inclusive_maximum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value less than or equal to " "Invalid value for `%s`, must be a value less than or equal to "
"`%s`" % ( "`%s`" % (
@@ -139,7 +295,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('exclusive_minimum' in current_validations and if ('exclusive_minimum' in current_validations and
input_values <= current_validations['exclusive_minimum']): min_val <= current_validations['exclusive_minimum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value greater than `%s`" % "Invalid value for `%s`, must be a value greater than `%s`" %
( (
@@ -149,7 +305,7 @@ def check_validations(validations, input_variable_path, input_values):
) )
if ('inclusive_minimum' in current_validations and if ('inclusive_minimum' in current_validations and
input_values < current_validations['inclusive_minimum']): min_val < current_validations['inclusive_minimum']):
raise ApiValueError( raise ApiValueError(
"Invalid value for `%s`, must be a value greater than or equal " "Invalid value for `%s`, must be a value greater than or equal "
"to `%s`" % ( "to `%s`" % (
@@ -171,13 +327,550 @@ def check_validations(validations, input_variable_path, input_values):
) )
class ModelSimple(object): def order_response_types(required_types):
# the parent class of models whose type != object in their swagger/openapi """Returns the required types sorted in coercion order
# spec
pass Args:
required_types (list/tuple): collection of classes or instance of
list or dict with classs information inside it
Returns:
(list): coercion order sorted collection of classes or instance
of list or dict with classs information inside it
"""
def index_getter(class_or_instance):
if isinstance(class_or_instance, list):
return COERCION_INDEX_BY_TYPE[list]
elif isinstance(class_or_instance, dict):
return COERCION_INDEX_BY_TYPE[dict]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelNormal)):
return COERCION_INDEX_BY_TYPE[ModelNormal]
elif (inspect.isclass(class_or_instance)
and issubclass(class_or_instance, ModelSimple)):
return COERCION_INDEX_BY_TYPE[ModelSimple]
return COERCION_INDEX_BY_TYPE[class_or_instance]
sorted_types = sorted(
required_types,
key=lambda class_or_instance: index_getter(class_or_instance)
)
return sorted_types
class ModelNormal(object): def remove_uncoercible(required_types_classes, current_item, from_server,
# the parent class of models whose type == object in their swagger/openapi must_convert=True):
# spec """Only keeps the type conversions that are possible
pass
Args:
required_types_classes (tuple): tuple of classes that are required
these should be ordered by COERCION_INDEX_BY_TYPE
from_server (bool): a boolean of whether the data is from the server
if false, the data is from the client
current_item (any): the current item to be converted
Keyword Args:
must_convert (bool): if True the item to convert is of the wrong
type and we want a big list of coercibles
if False, we want a limited list of coercibles
Returns:
(list): the remaining coercible required types, classes only
"""
current_type_simple = get_simple_class(current_item)
results_classes = []
for required_type_class in required_types_classes:
# convert our models to OpenApiModel
required_type_class_simplified = required_type_class
if isinstance(required_type_class_simplified, type):
if issubclass(required_type_class_simplified, ModelNormal):
required_type_class_simplified = ModelNormal
elif issubclass(required_type_class_simplified, ModelSimple):
required_type_class_simplified = ModelSimple
if required_type_class_simplified == current_type_simple:
# don't consider converting to one's own class
continue
class_pair = (current_type_simple, required_type_class_simplified)
if must_convert and class_pair in COERCIBLE_TYPE_PAIRS[from_server]:
results_classes.append(required_type_class)
elif class_pair in UPCONVERSION_TYPE_PAIRS:
results_classes.append(required_type_class)
return results_classes
def get_required_type_classes(required_types_mixed):
"""Converts the tuple required_types into a tuple and a dict described
below
Args:
required_types_mixed (tuple/list): will contain either classes or
instance of list or dict
Returns:
(valid_classes, dict_valid_class_to_child_types_mixed):
valid_classes (tuple): the valid classes that the current item
should be
dict_valid_class_to_child_types_mixed (doct):
valid_class (class): this is the key
child_types_mixed (list/dict/tuple): describes the valid child
types
"""
valid_classes = []
child_req_types_by_current_type = {}
for required_type in required_types_mixed:
if isinstance(required_type, list):
valid_classes.append(list)
child_req_types_by_current_type[list] = required_type
elif isinstance(required_type, tuple):
valid_classes.append(tuple)
child_req_types_by_current_type[tuple] = required_type
elif isinstance(required_type, dict):
valid_classes.append(dict)
child_req_types_by_current_type[dict] = required_type[str]
else:
valid_classes.append(required_type)
return tuple(valid_classes), child_req_types_by_current_type
def change_keys_js_to_python(input_dict, model_class):
"""
Converts from javascript_key keys in the input_dict to python_keys in
the output dict using the mapping in model_class
"""
output_dict = {}
reversed_attr_map = {value: key for key, value in
six.iteritems(model_class.attribute_map)}
for javascript_key, value in six.iteritems(input_dict):
python_key = reversed_attr_map.get(javascript_key)
if python_key is None:
# if the key is unknown, it is in error or it is an
# additionalProperties variable
python_key = javascript_key
output_dict[python_key] = value
return output_dict
def get_type_error(var_value, path_to_item, valid_classes, key_type=False):
error_msg = type_error_message(
var_name=path_to_item[-1],
var_value=var_value,
valid_classes=valid_classes,
key_type=key_type
)
return ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=valid_classes,
key_type=key_type
)
def deserialize_primitive(data, klass, path_to_item):
"""Deserializes string to primitive type.
:param data: str/int/float
:param klass: str/class the class to convert to
:return: int, float, str, bool, date, datetime
"""
additional_message = ""
try:
if klass in {datetime, date}:
additional_message = (
"If you need your parameter to have a fallback "
"string value, please set its type as `type: {}` in your "
"spec. That allows the value to be any type. "
)
if klass == datetime:
if len(data) < 8:
raise ValueError("This is not a datetime")
# The string should be in iso8601 datetime format.
parsed_datetime = parse(data)
date_only = (
parsed_datetime.hour == 0 and
parsed_datetime.minute == 0 and
parsed_datetime.second == 0 and
parsed_datetime.tzinfo is None and
8 <= len(data) <= 10
)
if date_only:
raise ValueError("This is a date, not a datetime")
return parsed_datetime
elif klass == date:
if len(data) < 8:
raise ValueError("This is not a date")
return parse(data).date()
else:
converted_value = klass(data)
if isinstance(data, str) and klass == float:
if str(converted_value) != data:
# '7' -> 7.0 -> '7.0' != '7'
raise ValueError('This is not a float')
return converted_value
except (OverflowError, ValueError):
# parse can raise OverflowError
raise ApiValueError(
"{0}Failed to parse {1} as {2}".format(
additional_message, repr(data), get_py3_class_name(klass)
),
path_to_item=path_to_item
)
def deserialize_model(model_data, model_class, path_to_item, check_type,
configuration, from_server):
"""Deserializes model_data to model instance.
Args:
model_data (list/dict): data to instantiate the model
model_class (OpenApiModel): the model class
path_to_item (list): path to the model in the received data
check_type (bool): whether to check the data tupe for the values in
the model
configuration (Configuration): the instance to use to convert files
from_server (bool): True if the data is from the server
False if the data is from the client
Returns:
model instance
Raise:
ApiTypeError
ApiValueError
ApiKeyError
"""
fixed_model_data = copy.deepcopy(model_data)
if isinstance(fixed_model_data, dict):
fixed_model_data = change_keys_js_to_python(fixed_model_data,
model_class)
kw_args = dict(_check_type=check_type,
_path_to_item=path_to_item,
_configuration=configuration,
_from_server=from_server)
if hasattr(model_class, 'get_real_child_model'):
# discriminator case
discriminator_class = model_class.get_real_child_model(model_data)
if discriminator_class:
if isinstance(model_data, list):
instance = discriminator_class(*model_data, **kw_args)
elif isinstance(model_data, dict):
fixed_model_data = change_keys_js_to_python(
fixed_model_data,
discriminator_class
)
kw_args.update(fixed_model_data)
instance = discriminator_class(**kw_args)
else:
# all other cases
if isinstance(model_data, list):
instance = model_class(*model_data, **kw_args)
if isinstance(model_data, dict):
fixed_model_data = change_keys_js_to_python(fixed_model_data,
model_class)
kw_args.update(fixed_model_data)
instance = model_class(**kw_args)
else:
instance = model_class(model_data, **kw_args)
return instance
def deserialize_file(response_data, configuration, content_disposition=None):
"""Deserializes body to file
Saves response body into a file in a temporary folder,
using the filename from the `Content-Disposition` header if provided.
Args:
param response_data (str): the file data to write
configuration (Configuration): the instance to use to convert files
Keyword Args:
content_disposition (str): the value of the Content-Disposition
header
Returns:
(file_type): the deserialized file which is open
The user is responsible for closing and reading the file
"""
fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
os.close(fd)
os.remove(path)
if content_disposition:
filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
content_disposition).group(1)
path = os.path.join(os.path.dirname(path), filename)
with open(path, "wb") as f:
if six.PY3 and isinstance(response_data, str):
# in python3 change str to bytes so we can write it
response_data = response_data.encode('utf-8')
f.write(response_data)
f = open(path, "rb")
return f
def attempt_convert_item(input_value, valid_classes, path_to_item,
configuration, from_server, key_type=False,
must_convert=False, check_type=True):
"""
Args:
input_value (any): the data to convert
valid_classes (any): the classes that are valid
path_to_item (list): the path to the item to convert
configuration (Configuration): the instance to use to convert files
from_server (bool): True if data is from the server, False is data is
from the client
key_type (bool): if True we need to convert a key type (not supported)
must_convert (bool): if True we must convert
check_type (bool): if True we check the type or the returned data in
ModelNormal and ModelSimple instances
Returns:
instance (any) the fixed item
Raises:
ApiTypeError
ApiValueError
ApiKeyError
"""
valid_classes_ordered = order_response_types(valid_classes)
valid_classes_coercible = remove_uncoercible(
valid_classes_ordered, input_value, from_server)
if not valid_classes_coercible or key_type:
# we do not handle keytype errors, json will take care
# of this for us
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=key_type)
for valid_class in valid_classes_coercible:
try:
if issubclass(valid_class, OpenApiModel):
return deserialize_model(input_value, valid_class,
path_to_item, check_type,
configuration, from_server)
elif valid_class == file_type:
return deserialize_file(input_value, configuration)
return deserialize_primitive(input_value, valid_class,
path_to_item)
except (ApiTypeError, ApiValueError, ApiKeyError) as conversion_exc:
if must_convert:
raise conversion_exc
# if we have conversion errors when must_convert == False
# we ignore the exception and move on to the next class
continue
# we were unable to convert, must_convert == False
return input_value
def validate_and_convert_types(input_value, required_types_mixed, path_to_item,
from_server, _check_type, configuration=None):
"""Raises a TypeError is there is a problem, otherwise returns value
Args:
input_value (any): the data to validate/convert
required_types_mixed (list/dict/tuple): A list of
valid classes, or a list tuples of valid classes, or a dict where
the value is a tuple of value classes
path_to_item: (list) the path to the data being validated
this stores a list of keys or indices to get to the data being
validated
from_server (bool): True if data is from the server
False if data is from the client
_check_type: (boolean) if true, type will be checked and conversion
will be attempted.
configuration: (Configuration): the configuration class to use
when converting file_type items.
If passed, conversion will be attempted when possible
If not passed, no conversions will be attempted and
exceptions will be raised
Returns:
the correctly typed value
Raises:
ApiTypeError
"""
results = get_required_type_classes(required_types_mixed)
valid_classes, child_req_types_by_current_type = results
input_class_simple = get_simple_class(input_value)
valid_type = input_class_simple in set(valid_classes)
if not valid_type:
if configuration:
# if input_value is not valid_type try to convert it
converted_instance = attempt_convert_item(
input_value,
valid_classes,
path_to_item,
configuration,
from_server,
key_type=False,
must_convert=True
)
return converted_instance
else:
raise get_type_error(input_value, path_to_item, valid_classes,
key_type=False)
# input_value's type is in valid_classes
if len(valid_classes) > 1 and configuration:
# there are valid classes which are not the current class
valid_classes_coercible = remove_uncoercible(
valid_classes, input_value, from_server, must_convert=False)
if valid_classes_coercible:
converted_instance = attempt_convert_item(
input_value,
valid_classes_coercible,
path_to_item,
configuration,
from_server,
key_type=False,
must_convert=False
)
return converted_instance
if child_req_types_by_current_type == {}:
# all types are of the required types and there are no more inner
# variables left to look at
return input_value
inner_required_types = child_req_types_by_current_type.get(
type(input_value)
)
if inner_required_types is None:
# for this type, there are not more inner variables left to look at
return input_value
if isinstance(input_value, list):
if input_value == []:
# allow an empty list
return input_value
for index, inner_value in enumerate(input_value):
inner_path = list(path_to_item)
inner_path.append(index)
input_value[index] = validate_and_convert_types(
inner_value,
inner_required_types,
inner_path,
from_server,
_check_type,
configuration=configuration
)
elif isinstance(input_value, dict):
if input_value == {}:
# allow an empty dict
return input_value
for inner_key, inner_val in six.iteritems(input_value):
inner_path = list(path_to_item)
inner_path.append(inner_key)
if get_simple_class(inner_key) != str:
raise get_type_error(inner_key, inner_path, valid_classes,
key_type=True)
input_value[inner_key] = validate_and_convert_types(
inner_val,
inner_required_types,
inner_path,
from_server,
_check_type,
configuration=configuration
)
return input_value
def model_to_dict(model_instance, serialize=True):
"""Returns the model properties as a dict
Args:
model_instance (one of your model instances): the model instance that
will be converted to a dict.
Keyword Args:
serialize (bool): if True, the keys in the dict will be values from
attribute_map
"""
result = {}
for attr, value in six.iteritems(model_instance._data_store):
if serialize:
# we use get here because additional property key names do not
# exist in attribute_map
attr = model_instance.attribute_map.get(attr, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: model_to_dict(x, serialize=serialize)
if hasattr(x, '_data_store') else x, value
))
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0],
model_to_dict(item[1], serialize=serialize))
if hasattr(item[1], '_data_store') else item,
value.items()
))
elif hasattr(value, '_data_store'):
result[attr] = model_to_dict(value, serialize=serialize)
else:
result[attr] = value
return result
def type_error_message(var_value=None, var_name=None, valid_classes=None,
key_type=None):
"""
Keyword Args:
var_value (any): the variable which has the type_error
var_name (str): the name of the variable which has the typ error
valid_classes (tuple): the accepted classes for current_item's
value
key_type (bool): False if our value is a value in a dict
True if it is a key in a dict
False if our item is an item in a list
"""
key_or_value = 'value'
if key_type:
key_or_value = 'key'
valid_classes_phrase = get_valid_classes_phrase(valid_classes)
msg = (
"Invalid type for variable '{0}'. Required {1} type {2} and "
"passed type was {3}".format(
var_name,
key_or_value,
valid_classes_phrase,
type(var_value).__name__,
)
)
return msg
def get_valid_classes_phrase(input_classes):
"""Returns a string phrase describing what types are allowed
Note: Adds the extra valid classes in python2
"""
all_classes = list(input_classes)
if six.PY2 and str in input_classes:
all_classes.extend([str_py2, unicode_py2])
if six.PY2 and int in input_classes:
all_classes.extend([int_py2, long_py2])
all_classes = sorted(all_classes, key=lambda cls: cls.__name__)
all_class_names = [cls.__name__ for cls in all_classes]
if len(all_class_names) == 1:
return 'is {0}'.format(all_class_names[0])
return "is one of [{0}]".format(", ".join(all_class_names))
def get_py3_class_name(input_class):
if six.PY2:
if input_class == str:
return 'str'
elif input_class == int:
return 'int'
return input_class.__name__

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesAnyType(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesAnyType(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = (bool, date, datetime, dict, float, int, list, str,) # noqa: E501
"""AdditionalPropertiesAnyType - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesAnyType - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesAnyType. # noqa: E501 """Gets the name of this AdditionalPropertiesAnyType. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesAnyType. # noqa: E501 (str): The name of this AdditionalPropertiesAnyType. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesAnyType. """Sets the name of this AdditionalPropertiesAnyType. # noqa: E501
:param name: The name of this AdditionalPropertiesAnyType. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesAnyType(ModelNormal):
if not isinstance(other, AdditionalPropertiesAnyType): if not isinstance(other, AdditionalPropertiesAnyType):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesArray(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesArray(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = ([bool, date, datetime, dict, float, int, list, str],) # noqa: E501
"""AdditionalPropertiesArray - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesArray - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesArray. # noqa: E501 """Gets the name of this AdditionalPropertiesArray. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesArray. # noqa: E501 (str): The name of this AdditionalPropertiesArray. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesArray. """Sets the name of this AdditionalPropertiesArray. # noqa: E501
:param name: The name of this AdditionalPropertiesArray. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesArray(ModelNormal):
if not isinstance(other, AdditionalPropertiesArray): if not isinstance(other, AdditionalPropertiesArray):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesBoolean(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesBoolean(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = (bool,) # noqa: E501
"""AdditionalPropertiesBoolean - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesBoolean - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesBoolean. # noqa: E501 """Gets the name of this AdditionalPropertiesBoolean. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesBoolean. # noqa: E501 (str): The name of this AdditionalPropertiesBoolean. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesBoolean. """Sets the name of this AdditionalPropertiesBoolean. # noqa: E501
:param name: The name of this AdditionalPropertiesBoolean. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesBoolean(ModelNormal):
if not isinstance(other, AdditionalPropertiesBoolean): if not isinstance(other, AdditionalPropertiesBoolean):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesClass(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -66,359 +82,302 @@ class AdditionalPropertiesClass(ModelNormal):
} }
openapi_types = { openapi_types = {
'map_string': 'dict(str, str)', 'map_string': ({str: (str,)},), # noqa: E501
'map_number': 'dict(str, float)', 'map_number': ({str: (float,)},), # noqa: E501
'map_integer': 'dict(str, int)', 'map_integer': ({str: (int,)},), # noqa: E501
'map_boolean': 'dict(str, bool)', 'map_boolean': ({str: (bool,)},), # noqa: E501
'map_array_integer': 'dict(str, list[int])', 'map_array_integer': ({str: ([int],)},), # noqa: E501
'map_array_anytype': 'dict(str, list[object])', 'map_array_anytype': ({str: ([bool, date, datetime, dict, float, int, list, str],)},), # noqa: E501
'map_map_string': 'dict(str, dict(str, str))', 'map_map_string': ({str: ({str: (str,)},)},), # noqa: E501
'map_map_anytype': 'dict(str, dict(str, object))', 'map_map_anytype': ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)},), # noqa: E501
'anytype_1': 'object', 'anytype_1': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501
'anytype_2': 'object', 'anytype_2': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501
'anytype_3': 'object' 'anytype_3': (bool, date, datetime, dict, float, int, list, str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, map_string=None, map_number=None, map_integer=None, map_boolean=None, map_array_integer=None, map_array_anytype=None, map_map_string=None, map_map_anytype=None, anytype_1=None, anytype_2=None, anytype_3=None): # noqa: E501 additional_properties_type = None
"""AdditionalPropertiesClass - a model defined in OpenAPI""" # noqa: E501
self._map_string = None discriminator = None
self._map_number = None
self._map_integer = None
self._map_boolean = None
self._map_array_integer = None
self._map_array_anytype = None
self._map_map_string = None
self._map_map_anytype = None
self._anytype_1 = None
self._anytype_2 = None
self._anytype_3 = None
self.discriminator = None
if map_string is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.map_string = ( """AdditionalPropertiesClass - a model defined in OpenAPI
map_string
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
map_string ({str: (str,)}): [optional] # noqa: E501
map_number ({str: (float,)}): [optional] # noqa: E501
map_integer ({str: (int,)}): [optional] # noqa: E501
map_boolean ({str: (bool,)}): [optional] # noqa: E501
map_array_integer ({str: ([int],)}): [optional] # noqa: E501
map_array_anytype ({str: ([bool, date, datetime, dict, float, int, list, str],)}): [optional] # noqa: E501
map_map_string ({str: ({str: (str,)},)}): [optional] # noqa: E501
map_map_anytype ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}): [optional] # noqa: E501
anytype_1 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501
anytype_2 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501
anytype_3 (bool, date, datetime, dict, float, int, list, str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if map_number is not None: elif self.additional_properties_type is not None:
self.map_number = ( required_types_mixed = self.additional_properties_type
map_number
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if map_integer is not None: raise ApiTypeError(
self.map_integer = ( error_msg,
map_integer path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if map_boolean is not None:
self.map_boolean = ( if self._check_type:
map_boolean value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if map_array_integer is not None: if (name,) in self.validations:
self.map_array_integer = ( check_validations(
map_array_integer self.validations,
) (name,),
if map_array_anytype is not None: value
self.map_array_anytype = (
map_array_anytype
)
if map_map_string is not None:
self.map_map_string = (
map_map_string
)
if map_map_anytype is not None:
self.map_map_anytype = (
map_map_anytype
)
if anytype_1 is not None:
self.anytype_1 = (
anytype_1
)
if anytype_2 is not None:
self.anytype_2 = (
anytype_2
)
if anytype_3 is not None:
self.anytype_3 = (
anytype_3
) )
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def map_string(self): def map_string(self):
"""Gets the map_string of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_string of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_string of this AdditionalPropertiesClass. # noqa: E501 ({str: (str,)}): The map_string of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, str)
""" """
return self._map_string return self.__get_item('map_string')
@map_string.setter @map_string.setter
def map_string(self, map_string): # noqa: E501 def map_string(self, value):
"""Sets the map_string of this AdditionalPropertiesClass. """Sets the map_string of this AdditionalPropertiesClass. # noqa: E501
:param map_string: The map_string of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, str)
""" """
return self.__set_item('map_string', value)
self._map_string = (
map_string
)
@property @property
def map_number(self): def map_number(self):
"""Gets the map_number of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_number of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_number of this AdditionalPropertiesClass. # noqa: E501 ({str: (float,)}): The map_number of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, float)
""" """
return self._map_number return self.__get_item('map_number')
@map_number.setter @map_number.setter
def map_number(self, map_number): # noqa: E501 def map_number(self, value):
"""Sets the map_number of this AdditionalPropertiesClass. """Sets the map_number of this AdditionalPropertiesClass. # noqa: E501
:param map_number: The map_number of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, float)
""" """
return self.__set_item('map_number', value)
self._map_number = (
map_number
)
@property @property
def map_integer(self): def map_integer(self):
"""Gets the map_integer of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_integer of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_integer of this AdditionalPropertiesClass. # noqa: E501 ({str: (int,)}): The map_integer of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, int)
""" """
return self._map_integer return self.__get_item('map_integer')
@map_integer.setter @map_integer.setter
def map_integer(self, map_integer): # noqa: E501 def map_integer(self, value):
"""Sets the map_integer of this AdditionalPropertiesClass. """Sets the map_integer of this AdditionalPropertiesClass. # noqa: E501
:param map_integer: The map_integer of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, int)
""" """
return self.__set_item('map_integer', value)
self._map_integer = (
map_integer
)
@property @property
def map_boolean(self): def map_boolean(self):
"""Gets the map_boolean of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_boolean of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_boolean of this AdditionalPropertiesClass. # noqa: E501 ({str: (bool,)}): The map_boolean of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, bool)
""" """
return self._map_boolean return self.__get_item('map_boolean')
@map_boolean.setter @map_boolean.setter
def map_boolean(self, map_boolean): # noqa: E501 def map_boolean(self, value):
"""Sets the map_boolean of this AdditionalPropertiesClass. """Sets the map_boolean of this AdditionalPropertiesClass. # noqa: E501
:param map_boolean: The map_boolean of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, bool)
""" """
return self.__set_item('map_boolean', value)
self._map_boolean = (
map_boolean
)
@property @property
def map_array_integer(self): def map_array_integer(self):
"""Gets the map_array_integer of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_array_integer of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_array_integer of this AdditionalPropertiesClass. # noqa: E501 ({str: ([int],)}): The map_array_integer of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, list[int])
""" """
return self._map_array_integer return self.__get_item('map_array_integer')
@map_array_integer.setter @map_array_integer.setter
def map_array_integer(self, map_array_integer): # noqa: E501 def map_array_integer(self, value):
"""Sets the map_array_integer of this AdditionalPropertiesClass. """Sets the map_array_integer of this AdditionalPropertiesClass. # noqa: E501
:param map_array_integer: The map_array_integer of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, list[int])
""" """
return self.__set_item('map_array_integer', value)
self._map_array_integer = (
map_array_integer
)
@property @property
def map_array_anytype(self): def map_array_anytype(self):
"""Gets the map_array_anytype of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_array_anytype of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_array_anytype of this AdditionalPropertiesClass. # noqa: E501 ({str: ([bool, date, datetime, dict, float, int, list, str],)}): The map_array_anytype of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, list[object])
""" """
return self._map_array_anytype return self.__get_item('map_array_anytype')
@map_array_anytype.setter @map_array_anytype.setter
def map_array_anytype(self, map_array_anytype): # noqa: E501 def map_array_anytype(self, value):
"""Sets the map_array_anytype of this AdditionalPropertiesClass. """Sets the map_array_anytype of this AdditionalPropertiesClass. # noqa: E501
:param map_array_anytype: The map_array_anytype of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, list[object])
""" """
return self.__set_item('map_array_anytype', value)
self._map_array_anytype = (
map_array_anytype
)
@property @property
def map_map_string(self): def map_map_string(self):
"""Gets the map_map_string of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_map_string of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_map_string of this AdditionalPropertiesClass. # noqa: E501 ({str: ({str: (str,)},)}): The map_map_string of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, dict(str, str))
""" """
return self._map_map_string return self.__get_item('map_map_string')
@map_map_string.setter @map_map_string.setter
def map_map_string(self, map_map_string): # noqa: E501 def map_map_string(self, value):
"""Sets the map_map_string of this AdditionalPropertiesClass. """Sets the map_map_string of this AdditionalPropertiesClass. # noqa: E501
:param map_map_string: The map_map_string of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, dict(str, str))
""" """
return self.__set_item('map_map_string', value)
self._map_map_string = (
map_map_string
)
@property @property
def map_map_anytype(self): def map_map_anytype(self):
"""Gets the map_map_anytype of this AdditionalPropertiesClass. # noqa: E501 """Gets the map_map_anytype of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map_map_anytype of this AdditionalPropertiesClass. # noqa: E501 ({str: ({str: (bool, date, datetime, dict, float, int, list, str,)},)}): The map_map_anytype of this AdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, dict(str, object))
""" """
return self._map_map_anytype return self.__get_item('map_map_anytype')
@map_map_anytype.setter @map_map_anytype.setter
def map_map_anytype(self, map_map_anytype): # noqa: E501 def map_map_anytype(self, value):
"""Sets the map_map_anytype of this AdditionalPropertiesClass. """Sets the map_map_anytype of this AdditionalPropertiesClass. # noqa: E501
:param map_map_anytype: The map_map_anytype of this AdditionalPropertiesClass. # noqa: E501
:type: dict(str, dict(str, object))
""" """
return self.__set_item('map_map_anytype', value)
self._map_map_anytype = (
map_map_anytype
)
@property @property
def anytype_1(self): def anytype_1(self):
"""Gets the anytype_1 of this AdditionalPropertiesClass. # noqa: E501 """Gets the anytype_1 of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The anytype_1 of this AdditionalPropertiesClass. # noqa: E501 (bool, date, datetime, dict, float, int, list, str): The anytype_1 of this AdditionalPropertiesClass. # noqa: E501
:rtype: object
""" """
return self._anytype_1 return self.__get_item('anytype_1')
@anytype_1.setter @anytype_1.setter
def anytype_1(self, anytype_1): # noqa: E501 def anytype_1(self, value):
"""Sets the anytype_1 of this AdditionalPropertiesClass. """Sets the anytype_1 of this AdditionalPropertiesClass. # noqa: E501
:param anytype_1: The anytype_1 of this AdditionalPropertiesClass. # noqa: E501
:type: object
""" """
return self.__set_item('anytype_1', value)
self._anytype_1 = (
anytype_1
)
@property @property
def anytype_2(self): def anytype_2(self):
"""Gets the anytype_2 of this AdditionalPropertiesClass. # noqa: E501 """Gets the anytype_2 of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The anytype_2 of this AdditionalPropertiesClass. # noqa: E501 (bool, date, datetime, dict, float, int, list, str): The anytype_2 of this AdditionalPropertiesClass. # noqa: E501
:rtype: object
""" """
return self._anytype_2 return self.__get_item('anytype_2')
@anytype_2.setter @anytype_2.setter
def anytype_2(self, anytype_2): # noqa: E501 def anytype_2(self, value):
"""Sets the anytype_2 of this AdditionalPropertiesClass. """Sets the anytype_2 of this AdditionalPropertiesClass. # noqa: E501
:param anytype_2: The anytype_2 of this AdditionalPropertiesClass. # noqa: E501
:type: object
""" """
return self.__set_item('anytype_2', value)
self._anytype_2 = (
anytype_2
)
@property @property
def anytype_3(self): def anytype_3(self):
"""Gets the anytype_3 of this AdditionalPropertiesClass. # noqa: E501 """Gets the anytype_3 of this AdditionalPropertiesClass. # noqa: E501
Returns:
:return: The anytype_3 of this AdditionalPropertiesClass. # noqa: E501 (bool, date, datetime, dict, float, int, list, str): The anytype_3 of this AdditionalPropertiesClass. # noqa: E501
:rtype: object
""" """
return self._anytype_3 return self.__get_item('anytype_3')
@anytype_3.setter @anytype_3.setter
def anytype_3(self, anytype_3): # noqa: E501 def anytype_3(self, value):
"""Sets the anytype_3 of this AdditionalPropertiesClass. """Sets the anytype_3 of this AdditionalPropertiesClass. # noqa: E501
:param anytype_3: The anytype_3 of this AdditionalPropertiesClass. # noqa: E501
:type: object
""" """
return self.__set_item('anytype_3', value)
self._anytype_3 = (
anytype_3
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -433,7 +392,22 @@ class AdditionalPropertiesClass(ModelNormal):
if not isinstance(other, AdditionalPropertiesClass): if not isinstance(other, AdditionalPropertiesClass):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesInteger(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesInteger(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = (int,) # noqa: E501
"""AdditionalPropertiesInteger - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesInteger - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesInteger. # noqa: E501 """Gets the name of this AdditionalPropertiesInteger. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesInteger. # noqa: E501 (str): The name of this AdditionalPropertiesInteger. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesInteger. """Sets the name of this AdditionalPropertiesInteger. # noqa: E501
:param name: The name of this AdditionalPropertiesInteger. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesInteger(ModelNormal):
if not isinstance(other, AdditionalPropertiesInteger): if not isinstance(other, AdditionalPropertiesInteger):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesNumber(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesNumber(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = (float,) # noqa: E501
"""AdditionalPropertiesNumber - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesNumber - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesNumber. # noqa: E501 """Gets the name of this AdditionalPropertiesNumber. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesNumber. # noqa: E501 (str): The name of this AdditionalPropertiesNumber. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesNumber. """Sets the name of this AdditionalPropertiesNumber. # noqa: E501
:param name: The name of this AdditionalPropertiesNumber. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesNumber(ModelNormal):
if not isinstance(other, AdditionalPropertiesNumber): if not isinstance(other, AdditionalPropertiesNumber):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesObject(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesObject(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = ({str: (bool, date, datetime, dict, float, int, list, str,)},) # noqa: E501
"""AdditionalPropertiesObject - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesObject - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesObject. # noqa: E501 """Gets the name of this AdditionalPropertiesObject. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesObject. # noqa: E501 (str): The name of this AdditionalPropertiesObject. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesObject. """Sets the name of this AdditionalPropertiesObject. # noqa: E501
:param name: The name of this AdditionalPropertiesObject. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesObject(ModelNormal):
if not isinstance(other, AdditionalPropertiesObject): if not isinstance(other, AdditionalPropertiesObject):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class AdditionalPropertiesString(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class AdditionalPropertiesString(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None): # noqa: E501 additional_properties_type = (str,) # noqa: E501
"""AdditionalPropertiesString - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """AdditionalPropertiesString - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this AdditionalPropertiesString. # noqa: E501 """Gets the name of this AdditionalPropertiesString. # noqa: E501
Returns:
:return: The name of this AdditionalPropertiesString. # noqa: E501 (str): The name of this AdditionalPropertiesString. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this AdditionalPropertiesString. """Sets the name of this AdditionalPropertiesString. # noqa: E501
:param name: The name of this AdditionalPropertiesString. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class AdditionalPropertiesString(ModelNormal):
if not isinstance(other, AdditionalPropertiesString): if not isinstance(other, AdditionalPropertiesString):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,29 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.cat import Cat
from petstore_api.models.dog import Dog
class Animal(ModelNormal): class Animal(ModelNormal):
@@ -46,6 +62,8 @@ class Animal(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,108 +75,165 @@ class Animal(ModelNormal):
} }
discriminator_value_class_map = { discriminator_value_class_map = {
'Dog': 'Dog', 'Dog': Dog,
'Cat': 'Cat' 'Cat': Cat
} }
openapi_types = { openapi_types = {
'class_name': 'str', 'class_name': (str,), # noqa: E501
'color': 'str' 'color': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, class_name=None, color='red'): # noqa: E501 additional_properties_type = None
"""Animal - a model defined in OpenAPI""" # noqa: E501
self._class_name = None discriminator = 'class_name'
self._color = None
self.discriminator = 'class_name'
self.class_name = class_name def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
if color is not None: """Animal - a model defined in OpenAPI
self.color = (
color Args:
class_name (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('class_name', class_name)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def class_name(self): def class_name(self):
"""Gets the class_name of this Animal. # noqa: E501 """Gets the class_name of this Animal. # noqa: E501
Returns:
:return: The class_name of this Animal. # noqa: E501 (str): The class_name of this Animal. # noqa: E501
:rtype: str
""" """
return self._class_name return self.__get_item('class_name')
@class_name.setter @class_name.setter
def class_name(self, class_name): # noqa: E501 def class_name(self, value):
"""Sets the class_name of this Animal. """Sets the class_name of this Animal. # noqa: E501
:param class_name: The class_name of this Animal. # noqa: E501
:type: str
""" """
if class_name is None: return self.__set_item('class_name', value)
raise ApiValueError("Invalid value for `class_name`, must not be `None`") # noqa: E501
self._class_name = (
class_name
)
@property @property
def color(self): def color(self):
"""Gets the color of this Animal. # noqa: E501 """Gets the color of this Animal. # noqa: E501
Returns:
:return: The color of this Animal. # noqa: E501 (str): The color of this Animal. # noqa: E501
:rtype: str
""" """
return self._color return self.__get_item('color')
@color.setter @color.setter
def color(self, color): # noqa: E501 def color(self, value):
"""Sets the color of this Animal. """Sets the color of this Animal. # noqa: E501
:param color: The color of this Animal. # noqa: E501
:type: str
""" """
return self.__set_item('color', value)
self._color = ( @classmethod
color def get_real_child_model(cls, data):
) """Returns the real base class specified by the discriminator
We assume that data has javascript keys
def get_real_child_model(self, data): """
"""Returns the real base class specified by the discriminator""" discriminator_key = cls.attribute_map[cls.discriminator]
discriminator_key = self.attribute_map[self.discriminator]
discriminator_value = data[discriminator_key] discriminator_value = data[discriminator_key]
return self.discriminator_value_class_map.get(discriminator_value) return cls.discriminator_value_class_map.get(discriminator_value)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -173,7 +248,22 @@ class Animal(ModelNormal):
if not isinstance(other, Animal): if not isinstance(other, Animal):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ApiResponse(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -58,127 +74,166 @@ class ApiResponse(ModelNormal):
} }
openapi_types = { openapi_types = {
'code': 'int', 'code': (int,), # noqa: E501
'type': 'str', 'type': (str,), # noqa: E501
'message': 'str' 'message': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, code=None, type=None, message=None): # noqa: E501 additional_properties_type = None
"""ApiResponse - a model defined in OpenAPI""" # noqa: E501
self._code = None discriminator = None
self._type = None
self._message = None
self.discriminator = None
if code is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.code = ( """ApiResponse - a model defined in OpenAPI
code
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
code (int): [optional] # noqa: E501
type (str): [optional] # noqa: E501
message (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if type is not None: elif self.additional_properties_type is not None:
self.type = ( required_types_mixed = self.additional_properties_type
type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if message is not None: raise ApiTypeError(
self.message = ( error_msg,
message path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def code(self): def code(self):
"""Gets the code of this ApiResponse. # noqa: E501 """Gets the code of this ApiResponse. # noqa: E501
Returns:
:return: The code of this ApiResponse. # noqa: E501 (int): The code of this ApiResponse. # noqa: E501
:rtype: int
""" """
return self._code return self.__get_item('code')
@code.setter @code.setter
def code(self, code): # noqa: E501 def code(self, value):
"""Sets the code of this ApiResponse. """Sets the code of this ApiResponse. # noqa: E501
:param code: The code of this ApiResponse. # noqa: E501
:type: int
""" """
return self.__set_item('code', value)
self._code = (
code
)
@property @property
def type(self): def type(self):
"""Gets the type of this ApiResponse. # noqa: E501 """Gets the type of this ApiResponse. # noqa: E501
Returns:
:return: The type of this ApiResponse. # noqa: E501 (str): The type of this ApiResponse. # noqa: E501
:rtype: str
""" """
return self._type return self.__get_item('type')
@type.setter @type.setter
def type(self, type): # noqa: E501 def type(self, value):
"""Sets the type of this ApiResponse. """Sets the type of this ApiResponse. # noqa: E501
:param type: The type of this ApiResponse. # noqa: E501
:type: str
""" """
return self.__set_item('type', value)
self._type = (
type
)
@property @property
def message(self): def message(self):
"""Gets the message of this ApiResponse. # noqa: E501 """Gets the message of this ApiResponse. # noqa: E501
Returns:
:return: The message of this ApiResponse. # noqa: E501 (str): The message of this ApiResponse. # noqa: E501
:rtype: str
""" """
return self._message return self.__get_item('message')
@message.setter @message.setter
def message(self, message): # noqa: E501 def message(self, value):
"""Sets the message of this ApiResponse. """Sets the message of this ApiResponse. # noqa: E501
:param message: The message of this ApiResponse. # noqa: E501
:type: str
""" """
return self.__set_item('message', value)
self._message = (
message
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -193,7 +248,22 @@ class ApiResponse(ModelNormal):
if not isinstance(other, ApiResponse): if not isinstance(other, ApiResponse):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ArrayOfArrayOfNumberOnly(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class ArrayOfArrayOfNumberOnly(ModelNormal):
} }
openapi_types = { openapi_types = {
'array_array_number': 'list[list[float]]' 'array_array_number': ([[float]],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, array_array_number=None): # noqa: E501 additional_properties_type = None
"""ArrayOfArrayOfNumberOnly - a model defined in OpenAPI""" # noqa: E501
self._array_array_number = None discriminator = None
self.discriminator = None
if array_array_number is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.array_array_number = ( """ArrayOfArrayOfNumberOnly - a model defined in OpenAPI
array_array_number
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
array_array_number ([[float]]): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def array_array_number(self): def array_array_number(self):
"""Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 """Gets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501
Returns:
:return: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501 ([[float]]): The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501
:rtype: list[list[float]]
""" """
return self._array_array_number return self.__get_item('array_array_number')
@array_array_number.setter @array_array_number.setter
def array_array_number(self, array_array_number): # noqa: E501 def array_array_number(self, value):
"""Sets the array_array_number of this ArrayOfArrayOfNumberOnly. """Sets the array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501
:param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. # noqa: E501
:type: list[list[float]]
""" """
return self.__set_item('array_array_number', value)
self._array_array_number = (
array_array_number
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class ArrayOfArrayOfNumberOnly(ModelNormal):
if not isinstance(other, ArrayOfArrayOfNumberOnly): if not isinstance(other, ArrayOfArrayOfNumberOnly):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ArrayOfNumberOnly(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class ArrayOfNumberOnly(ModelNormal):
} }
openapi_types = { openapi_types = {
'array_number': 'list[float]' 'array_number': ([float],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, array_number=None): # noqa: E501 additional_properties_type = None
"""ArrayOfNumberOnly - a model defined in OpenAPI""" # noqa: E501
self._array_number = None discriminator = None
self.discriminator = None
if array_number is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.array_number = ( """ArrayOfNumberOnly - a model defined in OpenAPI
array_number
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
array_number ([float]): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def array_number(self): def array_number(self):
"""Gets the array_number of this ArrayOfNumberOnly. # noqa: E501 """Gets the array_number of this ArrayOfNumberOnly. # noqa: E501
Returns:
:return: The array_number of this ArrayOfNumberOnly. # noqa: E501 ([float]): The array_number of this ArrayOfNumberOnly. # noqa: E501
:rtype: list[float]
""" """
return self._array_number return self.__get_item('array_number')
@array_number.setter @array_number.setter
def array_number(self, array_number): # noqa: E501 def array_number(self, value):
"""Sets the array_number of this ArrayOfNumberOnly. """Sets the array_number of this ArrayOfNumberOnly. # noqa: E501
:param array_number: The array_number of this ArrayOfNumberOnly. # noqa: E501
:type: list[float]
""" """
return self.__set_item('array_number', value)
self._array_number = (
array_number
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class ArrayOfNumberOnly(ModelNormal):
if not isinstance(other, ArrayOfNumberOnly): if not isinstance(other, ArrayOfNumberOnly):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.read_only_first import ReadOnlyFirst
class ArrayTest(ModelNormal): class ArrayTest(ModelNormal):
@@ -46,6 +61,8 @@ class ArrayTest(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -58,127 +75,166 @@ class ArrayTest(ModelNormal):
} }
openapi_types = { openapi_types = {
'array_of_string': 'list[str]', 'array_of_string': ([str],), # noqa: E501
'array_array_of_integer': 'list[list[int]]', 'array_array_of_integer': ([[int]],), # noqa: E501
'array_array_of_model': 'list[list[ReadOnlyFirst]]' 'array_array_of_model': ([[ReadOnlyFirst]],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, array_of_string=None, array_array_of_integer=None, array_array_of_model=None): # noqa: E501 additional_properties_type = None
"""ArrayTest - a model defined in OpenAPI""" # noqa: E501
self._array_of_string = None discriminator = None
self._array_array_of_integer = None
self._array_array_of_model = None
self.discriminator = None
if array_of_string is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.array_of_string = ( """ArrayTest - a model defined in OpenAPI
array_of_string
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
array_of_string ([str]): [optional] # noqa: E501
array_array_of_integer ([[int]]): [optional] # noqa: E501
array_array_of_model ([[ReadOnlyFirst]]): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if array_array_of_integer is not None: elif self.additional_properties_type is not None:
self.array_array_of_integer = ( required_types_mixed = self.additional_properties_type
array_array_of_integer
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if array_array_of_model is not None: raise ApiTypeError(
self.array_array_of_model = ( error_msg,
array_array_of_model path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def array_of_string(self): def array_of_string(self):
"""Gets the array_of_string of this ArrayTest. # noqa: E501 """Gets the array_of_string of this ArrayTest. # noqa: E501
Returns:
:return: The array_of_string of this ArrayTest. # noqa: E501 ([str]): The array_of_string of this ArrayTest. # noqa: E501
:rtype: list[str]
""" """
return self._array_of_string return self.__get_item('array_of_string')
@array_of_string.setter @array_of_string.setter
def array_of_string(self, array_of_string): # noqa: E501 def array_of_string(self, value):
"""Sets the array_of_string of this ArrayTest. """Sets the array_of_string of this ArrayTest. # noqa: E501
:param array_of_string: The array_of_string of this ArrayTest. # noqa: E501
:type: list[str]
""" """
return self.__set_item('array_of_string', value)
self._array_of_string = (
array_of_string
)
@property @property
def array_array_of_integer(self): def array_array_of_integer(self):
"""Gets the array_array_of_integer of this ArrayTest. # noqa: E501 """Gets the array_array_of_integer of this ArrayTest. # noqa: E501
Returns:
:return: The array_array_of_integer of this ArrayTest. # noqa: E501 ([[int]]): The array_array_of_integer of this ArrayTest. # noqa: E501
:rtype: list[list[int]]
""" """
return self._array_array_of_integer return self.__get_item('array_array_of_integer')
@array_array_of_integer.setter @array_array_of_integer.setter
def array_array_of_integer(self, array_array_of_integer): # noqa: E501 def array_array_of_integer(self, value):
"""Sets the array_array_of_integer of this ArrayTest. """Sets the array_array_of_integer of this ArrayTest. # noqa: E501
:param array_array_of_integer: The array_array_of_integer of this ArrayTest. # noqa: E501
:type: list[list[int]]
""" """
return self.__set_item('array_array_of_integer', value)
self._array_array_of_integer = (
array_array_of_integer
)
@property @property
def array_array_of_model(self): def array_array_of_model(self):
"""Gets the array_array_of_model of this ArrayTest. # noqa: E501 """Gets the array_array_of_model of this ArrayTest. # noqa: E501
Returns:
:return: The array_array_of_model of this ArrayTest. # noqa: E501 ([[ReadOnlyFirst]]): The array_array_of_model of this ArrayTest. # noqa: E501
:rtype: list[list[ReadOnlyFirst]]
""" """
return self._array_array_of_model return self.__get_item('array_array_of_model')
@array_array_of_model.setter @array_array_of_model.setter
def array_array_of_model(self, array_array_of_model): # noqa: E501 def array_array_of_model(self, value):
"""Sets the array_array_of_model of this ArrayTest. """Sets the array_array_of_model of this ArrayTest. # noqa: E501
:param array_array_of_model: The array_array_of_model of this ArrayTest. # noqa: E501
:type: list[list[ReadOnlyFirst]]
""" """
return self.__set_item('array_array_of_model', value)
self._array_array_of_model = (
array_array_of_model
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -193,7 +249,22 @@ class ArrayTest(ModelNormal):
if not isinstance(other, ArrayTest): if not isinstance(other, ArrayTest):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Capitalization(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -61,216 +77,219 @@ class Capitalization(ModelNormal):
} }
openapi_types = { openapi_types = {
'small_camel': 'str', 'small_camel': (str,), # noqa: E501
'capital_camel': 'str', 'capital_camel': (str,), # noqa: E501
'small_snake': 'str', 'small_snake': (str,), # noqa: E501
'capital_snake': 'str', 'capital_snake': (str,), # noqa: E501
'sca_eth_flow_points': 'str', 'sca_eth_flow_points': (str,), # noqa: E501
'att_name': 'str' 'att_name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, small_camel=None, capital_camel=None, small_snake=None, capital_snake=None, sca_eth_flow_points=None, att_name=None): # noqa: E501 additional_properties_type = None
"""Capitalization - a model defined in OpenAPI""" # noqa: E501
self._small_camel = None discriminator = None
self._capital_camel = None
self._small_snake = None
self._capital_snake = None
self._sca_eth_flow_points = None
self._att_name = None
self.discriminator = None
if small_camel is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.small_camel = ( """Capitalization - a model defined in OpenAPI
small_camel
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
small_camel (str): [optional] # noqa: E501
capital_camel (str): [optional] # noqa: E501
small_snake (str): [optional] # noqa: E501
capital_snake (str): [optional] # noqa: E501
sca_eth_flow_points (str): [optional] # noqa: E501
att_name (str): Name of the pet . [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if capital_camel is not None: elif self.additional_properties_type is not None:
self.capital_camel = ( required_types_mixed = self.additional_properties_type
capital_camel
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if small_snake is not None: raise ApiTypeError(
self.small_snake = ( error_msg,
small_snake path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if capital_snake is not None:
self.capital_snake = ( if self._check_type:
capital_snake value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if sca_eth_flow_points is not None: if (name,) in self.validations:
self.sca_eth_flow_points = ( check_validations(
sca_eth_flow_points self.validations,
) (name,),
if att_name is not None: value
self.att_name = (
att_name
) )
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def small_camel(self): def small_camel(self):
"""Gets the small_camel of this Capitalization. # noqa: E501 """Gets the small_camel of this Capitalization. # noqa: E501
Returns:
:return: The small_camel of this Capitalization. # noqa: E501 (str): The small_camel of this Capitalization. # noqa: E501
:rtype: str
""" """
return self._small_camel return self.__get_item('small_camel')
@small_camel.setter @small_camel.setter
def small_camel(self, small_camel): # noqa: E501 def small_camel(self, value):
"""Sets the small_camel of this Capitalization. """Sets the small_camel of this Capitalization. # noqa: E501
:param small_camel: The small_camel of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('small_camel', value)
self._small_camel = (
small_camel
)
@property @property
def capital_camel(self): def capital_camel(self):
"""Gets the capital_camel of this Capitalization. # noqa: E501 """Gets the capital_camel of this Capitalization. # noqa: E501
Returns:
:return: The capital_camel of this Capitalization. # noqa: E501 (str): The capital_camel of this Capitalization. # noqa: E501
:rtype: str
""" """
return self._capital_camel return self.__get_item('capital_camel')
@capital_camel.setter @capital_camel.setter
def capital_camel(self, capital_camel): # noqa: E501 def capital_camel(self, value):
"""Sets the capital_camel of this Capitalization. """Sets the capital_camel of this Capitalization. # noqa: E501
:param capital_camel: The capital_camel of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('capital_camel', value)
self._capital_camel = (
capital_camel
)
@property @property
def small_snake(self): def small_snake(self):
"""Gets the small_snake of this Capitalization. # noqa: E501 """Gets the small_snake of this Capitalization. # noqa: E501
Returns:
:return: The small_snake of this Capitalization. # noqa: E501 (str): The small_snake of this Capitalization. # noqa: E501
:rtype: str
""" """
return self._small_snake return self.__get_item('small_snake')
@small_snake.setter @small_snake.setter
def small_snake(self, small_snake): # noqa: E501 def small_snake(self, value):
"""Sets the small_snake of this Capitalization. """Sets the small_snake of this Capitalization. # noqa: E501
:param small_snake: The small_snake of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('small_snake', value)
self._small_snake = (
small_snake
)
@property @property
def capital_snake(self): def capital_snake(self):
"""Gets the capital_snake of this Capitalization. # noqa: E501 """Gets the capital_snake of this Capitalization. # noqa: E501
Returns:
:return: The capital_snake of this Capitalization. # noqa: E501 (str): The capital_snake of this Capitalization. # noqa: E501
:rtype: str
""" """
return self._capital_snake return self.__get_item('capital_snake')
@capital_snake.setter @capital_snake.setter
def capital_snake(self, capital_snake): # noqa: E501 def capital_snake(self, value):
"""Sets the capital_snake of this Capitalization. """Sets the capital_snake of this Capitalization. # noqa: E501
:param capital_snake: The capital_snake of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('capital_snake', value)
self._capital_snake = (
capital_snake
)
@property @property
def sca_eth_flow_points(self): def sca_eth_flow_points(self):
"""Gets the sca_eth_flow_points of this Capitalization. # noqa: E501 """Gets the sca_eth_flow_points of this Capitalization. # noqa: E501
Returns:
:return: The sca_eth_flow_points of this Capitalization. # noqa: E501 (str): The sca_eth_flow_points of this Capitalization. # noqa: E501
:rtype: str
""" """
return self._sca_eth_flow_points return self.__get_item('sca_eth_flow_points')
@sca_eth_flow_points.setter @sca_eth_flow_points.setter
def sca_eth_flow_points(self, sca_eth_flow_points): # noqa: E501 def sca_eth_flow_points(self, value):
"""Sets the sca_eth_flow_points of this Capitalization. """Sets the sca_eth_flow_points of this Capitalization. # noqa: E501
:param sca_eth_flow_points: The sca_eth_flow_points of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('sca_eth_flow_points', value)
self._sca_eth_flow_points = (
sca_eth_flow_points
)
@property @property
def att_name(self): def att_name(self):
"""Gets the att_name of this Capitalization. # noqa: E501 """Gets the att_name of this Capitalization. # noqa: E501
Name of the pet # noqa: E501 Name of the pet # noqa: E501
:return: The att_name of this Capitalization. # noqa: E501 Returns:
:rtype: str (str): The att_name of this Capitalization. # noqa: E501
""" """
return self._att_name return self.__get_item('att_name')
@att_name.setter @att_name.setter
def att_name(self, att_name): # noqa: E501 def att_name(self, value):
"""Sets the att_name of this Capitalization. """Sets the att_name of this Capitalization. # noqa: E501
Name of the pet # noqa: E501 Name of the pet # noqa: E501
:param att_name: The att_name of this Capitalization. # noqa: E501
:type: str
""" """
return self.__set_item('att_name', value)
self._att_name = (
att_name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -285,7 +304,22 @@ class Capitalization(ModelNormal):
if not isinstance(other, Capitalization): if not isinstance(other, Capitalization):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,79 +60,182 @@ class Cat(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
} }
attribute_map = { attribute_map = {
'class_name': 'className', # noqa: E501
'color': 'color', # noqa: E501
'declawed': 'declawed' # noqa: E501 'declawed': 'declawed' # noqa: E501
} }
openapi_types = { openapi_types = {
'declawed': 'bool' 'class_name': (str,), # noqa: E501
'color': (str,), # noqa: E501
'declawed': (bool,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, declawed=None): # noqa: E501 additional_properties_type = None
"""Cat - a model defined in OpenAPI""" # noqa: E501
self._declawed = None discriminator = None
self.discriminator = None
if declawed is not None: def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.declawed = ( """Cat - a model defined in OpenAPI
declawed
Args:
class_name (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
declawed (bool): [optional] # noqa: E501
color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('class_name', class_name)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property
def class_name(self):
"""Gets the class_name of this Cat. # noqa: E501
Returns:
(str): The class_name of this Cat. # noqa: E501
"""
return self.__get_item('class_name')
@class_name.setter
def class_name(self, value):
"""Sets the class_name of this Cat. # noqa: E501
"""
return self.__set_item('class_name', value)
@property
def color(self):
"""Gets the color of this Cat. # noqa: E501
Returns:
(str): The color of this Cat. # noqa: E501
"""
return self.__get_item('color')
@color.setter
def color(self, value):
"""Sets the color of this Cat. # noqa: E501
"""
return self.__set_item('color', value)
@property @property
def declawed(self): def declawed(self):
"""Gets the declawed of this Cat. # noqa: E501 """Gets the declawed of this Cat. # noqa: E501
Returns:
:return: The declawed of this Cat. # noqa: E501 (bool): The declawed of this Cat. # noqa: E501
:rtype: bool
""" """
return self._declawed return self.__get_item('declawed')
@declawed.setter @declawed.setter
def declawed(self, declawed): # noqa: E501 def declawed(self, value):
"""Sets the declawed of this Cat. """Sets the declawed of this Cat. # noqa: E501
:param declawed: The declawed of this Cat. # noqa: E501
:type: bool
""" """
return self.__set_item('declawed', value)
self._declawed = (
declawed
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +250,22 @@ class Cat(ModelNormal):
if not isinstance(other, Cat): if not isinstance(other, Cat):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class CatAllOf(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class CatAllOf(ModelNormal):
} }
openapi_types = { openapi_types = {
'declawed': 'bool' 'declawed': (bool,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, declawed=None): # noqa: E501 additional_properties_type = None
"""CatAllOf - a model defined in OpenAPI""" # noqa: E501
self._declawed = None discriminator = None
self.discriminator = None
if declawed is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.declawed = ( """CatAllOf - a model defined in OpenAPI
declawed
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
declawed (bool): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def declawed(self): def declawed(self):
"""Gets the declawed of this CatAllOf. # noqa: E501 """Gets the declawed of this CatAllOf. # noqa: E501
Returns:
:return: The declawed of this CatAllOf. # noqa: E501 (bool): The declawed of this CatAllOf. # noqa: E501
:rtype: bool
""" """
return self._declawed return self.__get_item('declawed')
@declawed.setter @declawed.setter
def declawed(self, declawed): # noqa: E501 def declawed(self, value):
"""Sets the declawed of this CatAllOf. """Sets the declawed of this CatAllOf. # noqa: E501
:param declawed: The declawed of this CatAllOf. # noqa: E501
:type: bool
""" """
return self.__set_item('declawed', value)
self._declawed = (
declawed
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class CatAllOf(ModelNormal):
if not isinstance(other, CatAllOf): if not isinstance(other, CatAllOf):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Category(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,97 +73,151 @@ class Category(ModelNormal):
} }
openapi_types = { openapi_types = {
'id': 'int', 'id': (int,), # noqa: E501
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, id=None, name='default-name'): # noqa: E501 additional_properties_type = None
"""Category - a model defined in OpenAPI""" # noqa: E501
self._id = None discriminator = None
self._name = None
self.discriminator = None
if id is not None: def __init__(self, name='default-name', _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.id = ( """Category - a model defined in OpenAPI
id
Args:
Keyword Args:
name (str): defaults to 'default-name', must be one of ['default-name'] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (int): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('name', name)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
self.name = name elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def id(self): def id(self):
"""Gets the id of this Category. # noqa: E501 """Gets the id of this Category. # noqa: E501
Returns:
:return: The id of this Category. # noqa: E501 (int): The id of this Category. # noqa: E501
:rtype: int
""" """
return self._id return self.__get_item('id')
@id.setter @id.setter
def id(self, id): # noqa: E501 def id(self, value):
"""Sets the id of this Category. """Sets the id of this Category. # noqa: E501
:param id: The id of this Category. # noqa: E501
:type: int
""" """
return self.__set_item('id', value)
self._id = (
id
)
@property @property
def name(self): def name(self):
"""Gets the name of this Category. # noqa: E501 """Gets the name of this Category. # noqa: E501
Returns:
:return: The name of this Category. # noqa: E501 (str): The name of this Category. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this Category. """Sets the name of this Category. # noqa: E501
:param name: The name of this Category. # noqa: E501
:type: str
""" """
if name is None: return self.__set_item('name', value)
raise ApiValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -162,7 +232,22 @@ class Category(ModelNormal):
if not isinstance(other, Category): if not isinstance(other, Category):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ClassModel(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class ClassModel(ModelNormal):
} }
openapi_types = { openapi_types = {
'_class': 'str' '_class': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, _class=None): # noqa: E501 additional_properties_type = None
"""ClassModel - a model defined in OpenAPI""" # noqa: E501
self.__class = None discriminator = None
self.discriminator = None
if _class is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self._class = ( """ClassModel - a model defined in OpenAPI
_class
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_class (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def _class(self): def _class(self):
"""Gets the _class of this ClassModel. # noqa: E501 """Gets the _class of this ClassModel. # noqa: E501
Returns:
:return: The _class of this ClassModel. # noqa: E501 (str): The _class of this ClassModel. # noqa: E501
:rtype: str
""" """
return self.__class return self.__get_item('_class')
@_class.setter @_class.setter
def _class(self, _class): # noqa: E501 def _class(self, value):
"""Sets the _class of this ClassModel. """Sets the _class of this ClassModel. # noqa: E501
:param _class: The _class of this ClassModel. # noqa: E501
:type: str
""" """
return self.__set_item('_class', value)
self.__class = (
_class
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class ClassModel(ModelNormal):
if not isinstance(other, ClassModel): if not isinstance(other, ClassModel):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Client(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class Client(ModelNormal):
} }
openapi_types = { openapi_types = {
'client': 'str' 'client': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, client=None): # noqa: E501 additional_properties_type = None
"""Client - a model defined in OpenAPI""" # noqa: E501
self._client = None discriminator = None
self.discriminator = None
if client is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.client = ( """Client - a model defined in OpenAPI
client
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
client (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def client(self): def client(self):
"""Gets the client of this Client. # noqa: E501 """Gets the client of this Client. # noqa: E501
Returns:
:return: The client of this Client. # noqa: E501 (str): The client of this Client. # noqa: E501
:rtype: str
""" """
return self._client return self.__get_item('client')
@client.setter @client.setter
def client(self, client): # noqa: E501 def client(self, value):
"""Sets the client of this Client. """Sets the client of this Client. # noqa: E501
:param client: The client of this Client. # noqa: E501
:type: str
""" """
return self.__set_item('client', value)
self._client = (
client
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class Client(ModelNormal):
if not isinstance(other, Client): if not isinstance(other, Client):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,79 +60,182 @@ class Dog(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
} }
attribute_map = { attribute_map = {
'class_name': 'className', # noqa: E501
'color': 'color', # noqa: E501
'breed': 'breed' # noqa: E501 'breed': 'breed' # noqa: E501
} }
openapi_types = { openapi_types = {
'breed': 'str' 'class_name': (str,), # noqa: E501
'color': (str,), # noqa: E501
'breed': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, breed=None): # noqa: E501 additional_properties_type = None
"""Dog - a model defined in OpenAPI""" # noqa: E501
self._breed = None discriminator = None
self.discriminator = None
if breed is not None: def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.breed = ( """Dog - a model defined in OpenAPI
breed
Args:
class_name (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
breed (str): [optional] # noqa: E501
color (str): [optional] if omitted the server will use the default value of 'red' # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('class_name', class_name)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property
def class_name(self):
"""Gets the class_name of this Dog. # noqa: E501
Returns:
(str): The class_name of this Dog. # noqa: E501
"""
return self.__get_item('class_name')
@class_name.setter
def class_name(self, value):
"""Sets the class_name of this Dog. # noqa: E501
"""
return self.__set_item('class_name', value)
@property
def color(self):
"""Gets the color of this Dog. # noqa: E501
Returns:
(str): The color of this Dog. # noqa: E501
"""
return self.__get_item('color')
@color.setter
def color(self, value):
"""Sets the color of this Dog. # noqa: E501
"""
return self.__set_item('color', value)
@property @property
def breed(self): def breed(self):
"""Gets the breed of this Dog. # noqa: E501 """Gets the breed of this Dog. # noqa: E501
Returns:
:return: The breed of this Dog. # noqa: E501 (str): The breed of this Dog. # noqa: E501
:rtype: str
""" """
return self._breed return self.__get_item('breed')
@breed.setter @breed.setter
def breed(self, breed): # noqa: E501 def breed(self, value):
"""Sets the breed of this Dog. """Sets the breed of this Dog. # noqa: E501
:param breed: The breed of this Dog. # noqa: E501
:type: str
""" """
return self.__set_item('breed', value)
self._breed = (
breed
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +250,22 @@ class Dog(ModelNormal):
if not isinstance(other, Dog): if not isinstance(other, Dog):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class DogAllOf(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class DogAllOf(ModelNormal):
} }
openapi_types = { openapi_types = {
'breed': 'str' 'breed': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, breed=None): # noqa: E501 additional_properties_type = None
"""DogAllOf - a model defined in OpenAPI""" # noqa: E501
self._breed = None discriminator = None
self.discriminator = None
if breed is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.breed = ( """DogAllOf - a model defined in OpenAPI
breed
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
breed (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def breed(self): def breed(self):
"""Gets the breed of this DogAllOf. # noqa: E501 """Gets the breed of this DogAllOf. # noqa: E501
Returns:
:return: The breed of this DogAllOf. # noqa: E501 (str): The breed of this DogAllOf. # noqa: E501
:rtype: str
""" """
return self._breed return self.__get_item('breed')
@breed.setter @breed.setter
def breed(self, breed): # noqa: E501 def breed(self, value):
"""Sets the breed of this DogAllOf. """Sets the breed of this DogAllOf. # noqa: E501
:param breed: The breed of this DogAllOf. # noqa: E501
:type: str
""" """
return self.__set_item('breed', value)
self._breed = (
breed
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class DogAllOf(ModelNormal):
if not isinstance(other, DogAllOf): if not isinstance(other, DogAllOf):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,16 +60,18 @@ class EnumArrays(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('just_symbol',): { ('just_symbol',): {
'&gt;&#x3D;': ">=", '&gt;&#x3D;': ">=",
'$': "$" '$': "$",
}, },
('array_enum',): { ('array_enum',): {
'FISH': "fish", 'FISH': "fish",
'CRAB': "crab" 'CRAB': "crab",
}, },
} }
@@ -65,110 +81,149 @@ class EnumArrays(ModelNormal):
} }
openapi_types = { openapi_types = {
'just_symbol': 'str', 'just_symbol': (str,), # noqa: E501
'array_enum': 'list[str]' 'array_enum': ([str],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, just_symbol=None, array_enum=None): # noqa: E501 additional_properties_type = None
"""EnumArrays - a model defined in OpenAPI""" # noqa: E501
self._just_symbol = None discriminator = None
self._array_enum = None
self.discriminator = None
if just_symbol is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.just_symbol = ( """EnumArrays - a model defined in OpenAPI
just_symbol
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
just_symbol (str): [optional] # noqa: E501
array_enum ([str]): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if array_enum is not None: elif self.additional_properties_type is not None:
self.array_enum = ( required_types_mixed = self.additional_properties_type
array_enum
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def just_symbol(self): def just_symbol(self):
"""Gets the just_symbol of this EnumArrays. # noqa: E501 """Gets the just_symbol of this EnumArrays. # noqa: E501
Returns:
:return: The just_symbol of this EnumArrays. # noqa: E501 (str): The just_symbol of this EnumArrays. # noqa: E501
:rtype: str
""" """
return self._just_symbol return self.__get_item('just_symbol')
@just_symbol.setter @just_symbol.setter
def just_symbol(self, just_symbol): # noqa: E501 def just_symbol(self, value):
"""Sets the just_symbol of this EnumArrays. """Sets the just_symbol of this EnumArrays. # noqa: E501
:param just_symbol: The just_symbol of this EnumArrays. # noqa: E501
:type: str
""" """
check_allowed_values( return self.__set_item('just_symbol', value)
self.allowed_values,
('just_symbol',),
just_symbol,
self.validations
)
self._just_symbol = (
just_symbol
)
@property @property
def array_enum(self): def array_enum(self):
"""Gets the array_enum of this EnumArrays. # noqa: E501 """Gets the array_enum of this EnumArrays. # noqa: E501
Returns:
:return: The array_enum of this EnumArrays. # noqa: E501 ([str]): The array_enum of this EnumArrays. # noqa: E501
:rtype: list[str]
""" """
return self._array_enum return self.__get_item('array_enum')
@array_enum.setter @array_enum.setter
def array_enum(self, array_enum): # noqa: E501 def array_enum(self, value):
"""Sets the array_enum of this EnumArrays. """Sets the array_enum of this EnumArrays. # noqa: E501
:param array_enum: The array_enum of this EnumArrays. # noqa: E501
:type: list[str]
""" """
check_allowed_values( return self.__set_item('array_enum', value)
self.allowed_values,
('array_enum',),
array_enum,
self.validations
)
self._array_enum = (
array_enum
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -183,7 +238,22 @@ class EnumArrays(ModelNormal):
if not isinstance(other, EnumArrays): if not isinstance(other, EnumArrays):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -42,65 +56,147 @@ class EnumClass(ModelSimple):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('value',): { ('value',): {
'_ABC': "_abc", '_ABC': "_abc",
'-EFG': "-efg", '-EFG': "-efg",
'(XYZ)': "(xyz)" '(XYZ)': "(xyz)",
}, },
} }
openapi_types = { openapi_types = {
'value': 'str' 'value': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, value='-efg'): # noqa: E501 additional_properties_type = None
"""EnumClass - a model defined in OpenAPI""" # noqa: E501
self._value = None discriminator = None
self.discriminator = None
self.value = value def __init__(self, value='-efg', _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
"""EnumClass - a model defined in OpenAPI
Args:
Keyword Args:
value (str): defaults to '-efg', must be one of ['-efg'] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('value', value)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
)
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def value(self): def value(self):
"""Gets the value of this EnumClass. # noqa: E501 """Gets the value of this EnumClass. # noqa: E501
Returns:
:return: The value of this EnumClass. # noqa: E501 (str): The value of this EnumClass. # noqa: E501
:rtype: str
""" """
return self._value return self.__get_item('value')
@value.setter @value.setter
def value(self, value): # noqa: E501 def value(self, value):
"""Sets the value of this EnumClass. """Sets the value of this EnumClass. # noqa: E501
:param value: The value of this EnumClass. # noqa: E501
:type: str
""" """
if value is None: return self.__set_item('value', value)
raise ApiValueError("Invalid value for `value`, must not be `None`") # noqa: E501
check_allowed_values(
self.allowed_values,
('value',),
value,
self.validations
)
self._value = (
value
)
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
return str(self._value) return str(self.value)
def __repr__(self): def __repr__(self):
"""For `print` and `pprint`""" """For `print` and `pprint`"""
@@ -111,7 +207,19 @@ class EnumClass(ModelSimple):
if not isinstance(other, EnumClass): if not isinstance(other, EnumClass):
return False return False
return self.__dict__ == other.__dict__ this_val = self._data_store['value']
that_val = other._data_store['value']
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.outer_enum import OuterEnum
class EnumTest(ModelNormal): class EnumTest(ModelNormal):
@@ -46,26 +61,28 @@ class EnumTest(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('enum_string',): { ('enum_string',): {
'UPPER': "UPPER", 'UPPER': "UPPER",
'LOWER': "lower", 'LOWER': "lower",
'EMPTY': "" 'EMPTY': "",
}, },
('enum_string_required',): { ('enum_string_required',): {
'UPPER': "UPPER", 'UPPER': "UPPER",
'LOWER': "lower", 'LOWER': "lower",
'EMPTY': "" 'EMPTY': "",
}, },
('enum_integer',): { ('enum_integer',): {
'1': 1, '1': 1,
'-1': -1 '-1': -1,
}, },
('enum_number',): { ('enum_number',): {
'1.1': 1.1, '1.1': 1.1,
'-1.2': -1.2 '-1.2': -1.2,
}, },
} }
@@ -78,208 +95,202 @@ class EnumTest(ModelNormal):
} }
openapi_types = { openapi_types = {
'enum_string': 'str', 'enum_string': (str,), # noqa: E501
'enum_string_required': 'str', 'enum_string_required': (str,), # noqa: E501
'enum_integer': 'int', 'enum_integer': (int,), # noqa: E501
'enum_number': 'float', 'enum_number': (float,), # noqa: E501
'outer_enum': 'OuterEnum' 'outer_enum': (OuterEnum,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, enum_string=None, enum_string_required=None, enum_integer=None, enum_number=None, outer_enum=None): # noqa: E501 additional_properties_type = None
"""EnumTest - a model defined in OpenAPI""" # noqa: E501
self._enum_string = None discriminator = None
self._enum_string_required = None
self._enum_integer = None
self._enum_number = None
self._outer_enum = None
self.discriminator = None
if enum_string is not None: def __init__(self, enum_string_required, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.enum_string = ( """EnumTest - a model defined in OpenAPI
enum_string
Args:
enum_string_required (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
enum_string (str): [optional] # noqa: E501
enum_integer (int): [optional] # noqa: E501
enum_number (float): [optional] # noqa: E501
outer_enum (OuterEnum): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('enum_string_required', enum_string_required)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
self.enum_string_required = enum_string_required elif self.additional_properties_type is not None:
if enum_integer is not None: required_types_mixed = self.additional_properties_type
self.enum_integer = (
enum_integer if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if enum_number is not None: raise ApiTypeError(
self.enum_number = ( error_msg,
enum_number path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if outer_enum is not None:
self.outer_enum = ( if self._check_type:
outer_enum value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def enum_string(self): def enum_string(self):
"""Gets the enum_string of this EnumTest. # noqa: E501 """Gets the enum_string of this EnumTest. # noqa: E501
Returns:
:return: The enum_string of this EnumTest. # noqa: E501 (str): The enum_string of this EnumTest. # noqa: E501
:rtype: str
""" """
return self._enum_string return self.__get_item('enum_string')
@enum_string.setter @enum_string.setter
def enum_string(self, enum_string): # noqa: E501 def enum_string(self, value):
"""Sets the enum_string of this EnumTest. """Sets the enum_string of this EnumTest. # noqa: E501
:param enum_string: The enum_string of this EnumTest. # noqa: E501
:type: str
""" """
check_allowed_values( return self.__set_item('enum_string', value)
self.allowed_values,
('enum_string',),
enum_string,
self.validations
)
self._enum_string = (
enum_string
)
@property @property
def enum_string_required(self): def enum_string_required(self):
"""Gets the enum_string_required of this EnumTest. # noqa: E501 """Gets the enum_string_required of this EnumTest. # noqa: E501
Returns:
:return: The enum_string_required of this EnumTest. # noqa: E501 (str): The enum_string_required of this EnumTest. # noqa: E501
:rtype: str
""" """
return self._enum_string_required return self.__get_item('enum_string_required')
@enum_string_required.setter @enum_string_required.setter
def enum_string_required(self, enum_string_required): # noqa: E501 def enum_string_required(self, value):
"""Sets the enum_string_required of this EnumTest. """Sets the enum_string_required of this EnumTest. # noqa: E501
:param enum_string_required: The enum_string_required of this EnumTest. # noqa: E501
:type: str
""" """
if enum_string_required is None: return self.__set_item('enum_string_required', value)
raise ApiValueError("Invalid value for `enum_string_required`, must not be `None`") # noqa: E501
check_allowed_values(
self.allowed_values,
('enum_string_required',),
enum_string_required,
self.validations
)
self._enum_string_required = (
enum_string_required
)
@property @property
def enum_integer(self): def enum_integer(self):
"""Gets the enum_integer of this EnumTest. # noqa: E501 """Gets the enum_integer of this EnumTest. # noqa: E501
Returns:
:return: The enum_integer of this EnumTest. # noqa: E501 (int): The enum_integer of this EnumTest. # noqa: E501
:rtype: int
""" """
return self._enum_integer return self.__get_item('enum_integer')
@enum_integer.setter @enum_integer.setter
def enum_integer(self, enum_integer): # noqa: E501 def enum_integer(self, value):
"""Sets the enum_integer of this EnumTest. """Sets the enum_integer of this EnumTest. # noqa: E501
:param enum_integer: The enum_integer of this EnumTest. # noqa: E501
:type: int
""" """
check_allowed_values( return self.__set_item('enum_integer', value)
self.allowed_values,
('enum_integer',),
enum_integer,
self.validations
)
self._enum_integer = (
enum_integer
)
@property @property
def enum_number(self): def enum_number(self):
"""Gets the enum_number of this EnumTest. # noqa: E501 """Gets the enum_number of this EnumTest. # noqa: E501
Returns:
:return: The enum_number of this EnumTest. # noqa: E501 (float): The enum_number of this EnumTest. # noqa: E501
:rtype: float
""" """
return self._enum_number return self.__get_item('enum_number')
@enum_number.setter @enum_number.setter
def enum_number(self, enum_number): # noqa: E501 def enum_number(self, value):
"""Sets the enum_number of this EnumTest. """Sets the enum_number of this EnumTest. # noqa: E501
:param enum_number: The enum_number of this EnumTest. # noqa: E501
:type: float
""" """
check_allowed_values( return self.__set_item('enum_number', value)
self.allowed_values,
('enum_number',),
enum_number,
self.validations
)
self._enum_number = (
enum_number
)
@property @property
def outer_enum(self): def outer_enum(self):
"""Gets the outer_enum of this EnumTest. # noqa: E501 """Gets the outer_enum of this EnumTest. # noqa: E501
Returns:
:return: The outer_enum of this EnumTest. # noqa: E501 (OuterEnum): The outer_enum of this EnumTest. # noqa: E501
:rtype: OuterEnum
""" """
return self._outer_enum return self.__get_item('outer_enum')
@outer_enum.setter @outer_enum.setter
def outer_enum(self, outer_enum): # noqa: E501 def outer_enum(self, value):
"""Sets the outer_enum of this EnumTest. """Sets the outer_enum of this EnumTest. # noqa: E501
:param outer_enum: The outer_enum of this EnumTest. # noqa: E501
:type: OuterEnum
""" """
return self.__set_item('outer_enum', value)
self._outer_enum = (
outer_enum
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -294,7 +305,22 @@ class EnumTest(ModelNormal):
if not isinstance(other, EnumTest): if not isinstance(other, EnumTest):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class File(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,71 +72,134 @@ class File(ModelNormal):
} }
openapi_types = { openapi_types = {
'source_uri': 'str' 'source_uri': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, source_uri=None): # noqa: E501 additional_properties_type = None
"""File - a model defined in OpenAPI""" # noqa: E501
self._source_uri = None discriminator = None
self.discriminator = None
if source_uri is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.source_uri = ( """File - a model defined in OpenAPI
source_uri
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
source_uri (str): Test capitalization. [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def source_uri(self): def source_uri(self):
"""Gets the source_uri of this File. # noqa: E501 """Gets the source_uri of this File. # noqa: E501
Test capitalization # noqa: E501 Test capitalization # noqa: E501
:return: The source_uri of this File. # noqa: E501 Returns:
:rtype: str (str): The source_uri of this File. # noqa: E501
""" """
return self._source_uri return self.__get_item('source_uri')
@source_uri.setter @source_uri.setter
def source_uri(self, source_uri): # noqa: E501 def source_uri(self, value):
"""Sets the source_uri of this File. """Sets the source_uri of this File. # noqa: E501
Test capitalization # noqa: E501 Test capitalization # noqa: E501
:param source_uri: The source_uri of this File. # noqa: E501
:type: str
""" """
return self.__set_item('source_uri', value)
self._source_uri = (
source_uri
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -135,7 +214,22 @@ class File(ModelNormal):
if not isinstance(other, File): if not isinstance(other, File):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.file import File
class FileSchemaTestClass(ModelNormal): class FileSchemaTestClass(ModelNormal):
@@ -46,6 +61,8 @@ class FileSchemaTestClass(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,98 +74,149 @@ class FileSchemaTestClass(ModelNormal):
} }
openapi_types = { openapi_types = {
'file': 'File', 'file': (File,), # noqa: E501
'files': 'list[File]' 'files': ([File],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, file=None, files=None): # noqa: E501 additional_properties_type = None
"""FileSchemaTestClass - a model defined in OpenAPI""" # noqa: E501
self._file = None discriminator = None
self._files = None
self.discriminator = None
if file is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.file = ( """FileSchemaTestClass - a model defined in OpenAPI
file
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
file (File): [optional] # noqa: E501
files ([File]): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if files is not None: elif self.additional_properties_type is not None:
self.files = ( required_types_mixed = self.additional_properties_type
files
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def file(self): def file(self):
"""Gets the file of this FileSchemaTestClass. # noqa: E501 """Gets the file of this FileSchemaTestClass. # noqa: E501
Returns:
:return: The file of this FileSchemaTestClass. # noqa: E501 (File): The file of this FileSchemaTestClass. # noqa: E501
:rtype: File
""" """
return self._file return self.__get_item('file')
@file.setter @file.setter
def file(self, file): # noqa: E501 def file(self, value):
"""Sets the file of this FileSchemaTestClass. """Sets the file of this FileSchemaTestClass. # noqa: E501
:param file: The file of this FileSchemaTestClass. # noqa: E501
:type: File
""" """
return self.__set_item('file', value)
self._file = (
file
)
@property @property
def files(self): def files(self):
"""Gets the files of this FileSchemaTestClass. # noqa: E501 """Gets the files of this FileSchemaTestClass. # noqa: E501
Returns:
:return: The files of this FileSchemaTestClass. # noqa: E501 ([File]): The files of this FileSchemaTestClass. # noqa: E501
:rtype: list[File]
""" """
return self._files return self.__get_item('files')
@files.setter @files.setter
def files(self, files): # noqa: E501 def files(self, value):
"""Sets the files of this FileSchemaTestClass. """Sets the files of this FileSchemaTestClass. # noqa: E501
:param files: The files of this FileSchemaTestClass. # noqa: E501
:type: list[File]
""" """
return self.__set_item('files', value)
self._files = (
files
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -163,7 +231,22 @@ class FileSchemaTestClass(ModelNormal):
if not isinstance(other, FileSchemaTestClass): if not isinstance(other, FileSchemaTestClass):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class FormatTest(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -68,56 +84,49 @@ class FormatTest(ModelNormal):
} }
openapi_types = { openapi_types = {
'integer': 'int', 'integer': (int,), # noqa: E501
'int32': 'int', 'int32': (int,), # noqa: E501
'int64': 'int', 'int64': (int,), # noqa: E501
'number': 'float', 'number': (float,), # noqa: E501
'float': 'float', 'float': (float,), # noqa: E501
'double': 'float', 'double': (float,), # noqa: E501
'string': 'str', 'string': (str,), # noqa: E501
'byte': 'str', 'byte': (str,), # noqa: E501
'binary': 'file', 'binary': (file_type,), # noqa: E501
'date': 'date', 'date': (date,), # noqa: E501
'date_time': 'datetime', 'date_time': (datetime,), # noqa: E501
'uuid': 'str', 'uuid': (str,), # noqa: E501
'password': 'str' 'password': (str,), # noqa: E501
} }
validations = { validations = {
('integer',): { ('integer',): {
'inclusive_maximum': 100, 'inclusive_maximum': 100,
'inclusive_minimum': 10, 'inclusive_minimum': 10,
}, },
('int32',): { ('int32',): {
'inclusive_maximum': 200, 'inclusive_maximum': 200,
'inclusive_minimum': 20, 'inclusive_minimum': 20,
}, },
('number',): { ('number',): {
'inclusive_maximum': 543.2, 'inclusive_maximum': 543.2,
'inclusive_minimum': 32.1, 'inclusive_minimum': 32.1,
}, },
('float',): { ('float',): {
'inclusive_maximum': 987.6, 'inclusive_maximum': 987.6,
'inclusive_minimum': 54.3, 'inclusive_minimum': 54.3,
}, },
('double',): { ('double',): {
'inclusive_maximum': 123.4, 'inclusive_maximum': 123.4,
'inclusive_minimum': 67.8, 'inclusive_minimum': 67.8,
}, },
('string',): { ('string',): {
'regex': { 'regex': {
'pattern': r'^[a-z]+$', # noqa: E501 'pattern': r'^[a-z]+$', # noqa: E501
'flags': (re.IGNORECASE) 'flags': (re.IGNORECASE)
}, },
}, },
('byte',): { ('byte',): {
'regex': { 'regex': {
'pattern': r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', # noqa: E501 'pattern': r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', # noqa: E501
}, },
@@ -128,435 +137,323 @@ class FormatTest(ModelNormal):
}, },
} }
def __init__(self, integer=None, int32=None, int64=None, number=None, float=None, double=None, string=None, byte=None, binary=None, date=None, date_time=None, uuid=None, password=None): # noqa: E501 additional_properties_type = None
"""FormatTest - a model defined in OpenAPI""" # noqa: E501
self._integer = None discriminator = None
self._int32 = None
self._int64 = None
self._number = None
self._float = None
self._double = None
self._string = None
self._byte = None
self._binary = None
self._date = None
self._date_time = None
self._uuid = None
self._password = None
self.discriminator = None
if integer is not None: def __init__(self, number, byte, date, password, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.integer = ( """FormatTest - a model defined in OpenAPI
integer
Args:
number (float):
byte (str):
date (date):
password (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
integer (int): [optional] # noqa: E501
int32 (int): [optional] # noqa: E501
int64 (int): [optional] # noqa: E501
float (float): [optional] # noqa: E501
double (float): [optional] # noqa: E501
string (str): [optional] # noqa: E501
binary (file_type): [optional] # noqa: E501
date_time (datetime): [optional] # noqa: E501
uuid (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('number', number)
self.__set_item('byte', byte)
self.__set_item('date', date)
self.__set_item('password', password)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if int32 is not None: elif self.additional_properties_type is not None:
self.int32 = ( required_types_mixed = self.additional_properties_type
int32
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if int64 is not None: raise ApiTypeError(
self.int64 = ( error_msg,
int64 path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
self.number = number
if float is not None: if self._check_type:
self.float = ( value = validate_and_convert_types(
float value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if double is not None: if (name,) in self.validations:
self.double = ( check_validations(
double self.validations,
(name,),
value
) )
if string is not None: self._data_store[name] = value
self.string = (
string def __get_item(self, name):
) if name in self._data_store:
self.byte = byte return self._data_store[name]
if binary is not None:
self.binary = ( path_to_item = []
binary if self._path_to_item:
) path_to_item.extend(self._path_to_item)
self.date = date path_to_item.append(name)
if date_time is not None: raise ApiKeyError(
self.date_time = ( "{0} has no key '{1}'".format(type(self).__name__, name),
date_time [name]
) )
if uuid is not None:
self.uuid = ( def __setitem__(self, name, value):
uuid """this allows us to set values with instance[field_name] = val"""
) self.__set_item(name, value)
self.password = password
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def integer(self): def integer(self):
"""Gets the integer of this FormatTest. # noqa: E501 """Gets the integer of this FormatTest. # noqa: E501
Returns:
:return: The integer of this FormatTest. # noqa: E501 (int): The integer of this FormatTest. # noqa: E501
:rtype: int
""" """
return self._integer return self.__get_item('integer')
@integer.setter @integer.setter
def integer(self, integer): # noqa: E501 def integer(self, value):
"""Sets the integer of this FormatTest. """Sets the integer of this FormatTest. # noqa: E501
:param integer: The integer of this FormatTest. # noqa: E501
:type: int
""" """
check_validations( return self.__set_item('integer', value)
self.validations,
('integer',),
integer
)
self._integer = (
integer
)
@property @property
def int32(self): def int32(self):
"""Gets the int32 of this FormatTest. # noqa: E501 """Gets the int32 of this FormatTest. # noqa: E501
Returns:
:return: The int32 of this FormatTest. # noqa: E501 (int): The int32 of this FormatTest. # noqa: E501
:rtype: int
""" """
return self._int32 return self.__get_item('int32')
@int32.setter @int32.setter
def int32(self, int32): # noqa: E501 def int32(self, value):
"""Sets the int32 of this FormatTest. """Sets the int32 of this FormatTest. # noqa: E501
:param int32: The int32 of this FormatTest. # noqa: E501
:type: int
""" """
check_validations( return self.__set_item('int32', value)
self.validations,
('int32',),
int32
)
self._int32 = (
int32
)
@property @property
def int64(self): def int64(self):
"""Gets the int64 of this FormatTest. # noqa: E501 """Gets the int64 of this FormatTest. # noqa: E501
Returns:
:return: The int64 of this FormatTest. # noqa: E501 (int): The int64 of this FormatTest. # noqa: E501
:rtype: int
""" """
return self._int64 return self.__get_item('int64')
@int64.setter @int64.setter
def int64(self, int64): # noqa: E501 def int64(self, value):
"""Sets the int64 of this FormatTest. """Sets the int64 of this FormatTest. # noqa: E501
:param int64: The int64 of this FormatTest. # noqa: E501
:type: int
""" """
return self.__set_item('int64', value)
self._int64 = (
int64
)
@property @property
def number(self): def number(self):
"""Gets the number of this FormatTest. # noqa: E501 """Gets the number of this FormatTest. # noqa: E501
Returns:
:return: The number of this FormatTest. # noqa: E501 (float): The number of this FormatTest. # noqa: E501
:rtype: float
""" """
return self._number return self.__get_item('number')
@number.setter @number.setter
def number(self, number): # noqa: E501 def number(self, value):
"""Sets the number of this FormatTest. """Sets the number of this FormatTest. # noqa: E501
:param number: The number of this FormatTest. # noqa: E501
:type: float
""" """
if number is None: return self.__set_item('number', value)
raise ApiValueError("Invalid value for `number`, must not be `None`") # noqa: E501
check_validations(
self.validations,
('number',),
number
)
self._number = (
number
)
@property @property
def float(self): def float(self):
"""Gets the float of this FormatTest. # noqa: E501 """Gets the float of this FormatTest. # noqa: E501
Returns:
:return: The float of this FormatTest. # noqa: E501 (float): The float of this FormatTest. # noqa: E501
:rtype: float
""" """
return self._float return self.__get_item('float')
@float.setter @float.setter
def float(self, float): # noqa: E501 def float(self, value):
"""Sets the float of this FormatTest. """Sets the float of this FormatTest. # noqa: E501
:param float: The float of this FormatTest. # noqa: E501
:type: float
""" """
check_validations( return self.__set_item('float', value)
self.validations,
('float',),
float
)
self._float = (
float
)
@property @property
def double(self): def double(self):
"""Gets the double of this FormatTest. # noqa: E501 """Gets the double of this FormatTest. # noqa: E501
Returns:
:return: The double of this FormatTest. # noqa: E501 (float): The double of this FormatTest. # noqa: E501
:rtype: float
""" """
return self._double return self.__get_item('double')
@double.setter @double.setter
def double(self, double): # noqa: E501 def double(self, value):
"""Sets the double of this FormatTest. """Sets the double of this FormatTest. # noqa: E501
:param double: The double of this FormatTest. # noqa: E501
:type: float
""" """
check_validations( return self.__set_item('double', value)
self.validations,
('double',),
double
)
self._double = (
double
)
@property @property
def string(self): def string(self):
"""Gets the string of this FormatTest. # noqa: E501 """Gets the string of this FormatTest. # noqa: E501
Returns:
:return: The string of this FormatTest. # noqa: E501 (str): The string of this FormatTest. # noqa: E501
:rtype: str
""" """
return self._string return self.__get_item('string')
@string.setter @string.setter
def string(self, string): # noqa: E501 def string(self, value):
"""Sets the string of this FormatTest. """Sets the string of this FormatTest. # noqa: E501
:param string: The string of this FormatTest. # noqa: E501
:type: str
""" """
check_validations( return self.__set_item('string', value)
self.validations,
('string',),
string
)
self._string = (
string
)
@property @property
def byte(self): def byte(self):
"""Gets the byte of this FormatTest. # noqa: E501 """Gets the byte of this FormatTest. # noqa: E501
Returns:
:return: The byte of this FormatTest. # noqa: E501 (str): The byte of this FormatTest. # noqa: E501
:rtype: str
""" """
return self._byte return self.__get_item('byte')
@byte.setter @byte.setter
def byte(self, byte): # noqa: E501 def byte(self, value):
"""Sets the byte of this FormatTest. """Sets the byte of this FormatTest. # noqa: E501
:param byte: The byte of this FormatTest. # noqa: E501
:type: str
""" """
if byte is None: return self.__set_item('byte', value)
raise ApiValueError("Invalid value for `byte`, must not be `None`") # noqa: E501
check_validations(
self.validations,
('byte',),
byte
)
self._byte = (
byte
)
@property @property
def binary(self): def binary(self):
"""Gets the binary of this FormatTest. # noqa: E501 """Gets the binary of this FormatTest. # noqa: E501
Returns:
:return: The binary of this FormatTest. # noqa: E501 (file_type): The binary of this FormatTest. # noqa: E501
:rtype: file
""" """
return self._binary return self.__get_item('binary')
@binary.setter @binary.setter
def binary(self, binary): # noqa: E501 def binary(self, value):
"""Sets the binary of this FormatTest. """Sets the binary of this FormatTest. # noqa: E501
:param binary: The binary of this FormatTest. # noqa: E501
:type: file
""" """
return self.__set_item('binary', value)
self._binary = (
binary
)
@property @property
def date(self): def date(self):
"""Gets the date of this FormatTest. # noqa: E501 """Gets the date of this FormatTest. # noqa: E501
Returns:
:return: The date of this FormatTest. # noqa: E501 (date): The date of this FormatTest. # noqa: E501
:rtype: date
""" """
return self._date return self.__get_item('date')
@date.setter @date.setter
def date(self, date): # noqa: E501 def date(self, value):
"""Sets the date of this FormatTest. """Sets the date of this FormatTest. # noqa: E501
:param date: The date of this FormatTest. # noqa: E501
:type: date
""" """
if date is None: return self.__set_item('date', value)
raise ApiValueError("Invalid value for `date`, must not be `None`") # noqa: E501
self._date = (
date
)
@property @property
def date_time(self): def date_time(self):
"""Gets the date_time of this FormatTest. # noqa: E501 """Gets the date_time of this FormatTest. # noqa: E501
Returns:
:return: The date_time of this FormatTest. # noqa: E501 (datetime): The date_time of this FormatTest. # noqa: E501
:rtype: datetime
""" """
return self._date_time return self.__get_item('date_time')
@date_time.setter @date_time.setter
def date_time(self, date_time): # noqa: E501 def date_time(self, value):
"""Sets the date_time of this FormatTest. """Sets the date_time of this FormatTest. # noqa: E501
:param date_time: The date_time of this FormatTest. # noqa: E501
:type: datetime
""" """
return self.__set_item('date_time', value)
self._date_time = (
date_time
)
@property @property
def uuid(self): def uuid(self):
"""Gets the uuid of this FormatTest. # noqa: E501 """Gets the uuid of this FormatTest. # noqa: E501
Returns:
:return: The uuid of this FormatTest. # noqa: E501 (str): The uuid of this FormatTest. # noqa: E501
:rtype: str
""" """
return self._uuid return self.__get_item('uuid')
@uuid.setter @uuid.setter
def uuid(self, uuid): # noqa: E501 def uuid(self, value):
"""Sets the uuid of this FormatTest. """Sets the uuid of this FormatTest. # noqa: E501
:param uuid: The uuid of this FormatTest. # noqa: E501
:type: str
""" """
return self.__set_item('uuid', value)
self._uuid = (
uuid
)
@property @property
def password(self): def password(self):
"""Gets the password of this FormatTest. # noqa: E501 """Gets the password of this FormatTest. # noqa: E501
Returns:
:return: The password of this FormatTest. # noqa: E501 (str): The password of this FormatTest. # noqa: E501
:rtype: str
""" """
return self._password return self.__get_item('password')
@password.setter @password.setter
def password(self, password): # noqa: E501 def password(self, value):
"""Sets the password of this FormatTest. """Sets the password of this FormatTest. # noqa: E501
:param password: The password of this FormatTest. # noqa: E501
:type: str
""" """
if password is None: return self.__set_item('password', value)
raise ApiValueError("Invalid value for `password`, must not be `None`") # noqa: E501
check_validations(
self.validations,
('password',),
password
)
self._password = (
password
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -571,7 +468,22 @@ class FormatTest(ModelNormal):
if not isinstance(other, FormatTest): if not isinstance(other, FormatTest):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class HasOnlyReadOnly(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,98 +73,149 @@ class HasOnlyReadOnly(ModelNormal):
} }
openapi_types = { openapi_types = {
'bar': 'str', 'bar': (str,), # noqa: E501
'foo': 'str' 'foo': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, bar=None, foo=None): # noqa: E501 additional_properties_type = None
"""HasOnlyReadOnly - a model defined in OpenAPI""" # noqa: E501
self._bar = None discriminator = None
self._foo = None
self.discriminator = None
if bar is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.bar = ( """HasOnlyReadOnly - a model defined in OpenAPI
bar
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
bar (str): [optional] # noqa: E501
foo (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if foo is not None: elif self.additional_properties_type is not None:
self.foo = ( required_types_mixed = self.additional_properties_type
foo
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def bar(self): def bar(self):
"""Gets the bar of this HasOnlyReadOnly. # noqa: E501 """Gets the bar of this HasOnlyReadOnly. # noqa: E501
Returns:
:return: The bar of this HasOnlyReadOnly. # noqa: E501 (str): The bar of this HasOnlyReadOnly. # noqa: E501
:rtype: str
""" """
return self._bar return self.__get_item('bar')
@bar.setter @bar.setter
def bar(self, bar): # noqa: E501 def bar(self, value):
"""Sets the bar of this HasOnlyReadOnly. """Sets the bar of this HasOnlyReadOnly. # noqa: E501
:param bar: The bar of this HasOnlyReadOnly. # noqa: E501
:type: str
""" """
return self.__set_item('bar', value)
self._bar = (
bar
)
@property @property
def foo(self): def foo(self):
"""Gets the foo of this HasOnlyReadOnly. # noqa: E501 """Gets the foo of this HasOnlyReadOnly. # noqa: E501
Returns:
:return: The foo of this HasOnlyReadOnly. # noqa: E501 (str): The foo of this HasOnlyReadOnly. # noqa: E501
:rtype: str
""" """
return self._foo return self.__get_item('foo')
@foo.setter @foo.setter
def foo(self, foo): # noqa: E501 def foo(self, value):
"""Sets the foo of this HasOnlyReadOnly. """Sets the foo of this HasOnlyReadOnly. # noqa: E501
:param foo: The foo of this HasOnlyReadOnly. # noqa: E501
:type: str
""" """
return self.__set_item('foo', value)
self._foo = (
foo
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -163,7 +230,22 @@ class HasOnlyReadOnly(ModelNormal):
if not isinstance(other, HasOnlyReadOnly): if not isinstance(other, HasOnlyReadOnly):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class List(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class List(ModelNormal):
} }
openapi_types = { openapi_types = {
'_123_list': 'str' '_123_list': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, _123_list=None): # noqa: E501 additional_properties_type = None
"""List - a model defined in OpenAPI""" # noqa: E501
self.__123_list = None discriminator = None
self.discriminator = None
if _123_list is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self._123_list = ( """List - a model defined in OpenAPI
_123_list
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_123_list (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def _123_list(self): def _123_list(self):
"""Gets the _123_list of this List. # noqa: E501 """Gets the _123_list of this List. # noqa: E501
Returns:
:return: The _123_list of this List. # noqa: E501 (str): The _123_list of this List. # noqa: E501
:rtype: str
""" """
return self.__123_list return self.__get_item('_123_list')
@_123_list.setter @_123_list.setter
def _123_list(self, _123_list): # noqa: E501 def _123_list(self, value):
"""Sets the _123_list of this List. """Sets the _123_list of this List. # noqa: E501
:param _123_list: The _123_list of this List. # noqa: E501
:type: str
""" """
return self.__set_item('_123_list', value)
self.__123_list = (
_123_list
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class List(ModelNormal):
if not isinstance(other, List): if not isinstance(other, List):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.string_boolean_map import StringBooleanMap
class MapTest(ModelNormal): class MapTest(ModelNormal):
@@ -46,12 +61,14 @@ class MapTest(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('map_of_enum_string',): { ('map_of_enum_string',): {
'UPPER': "UPPER", 'UPPER': "UPPER",
'LOWER': "lower" 'LOWER': "lower",
}, },
} }
@@ -63,162 +80,183 @@ class MapTest(ModelNormal):
} }
openapi_types = { openapi_types = {
'map_map_of_string': 'dict(str, dict(str, str))', 'map_map_of_string': ({str: ({str: (str,)},)},), # noqa: E501
'map_of_enum_string': 'dict(str, str)', 'map_of_enum_string': ({str: (str,)},), # noqa: E501
'direct_map': 'dict(str, bool)', 'direct_map': ({str: (bool,)},), # noqa: E501
'indirect_map': 'StringBooleanMap' 'indirect_map': (StringBooleanMap,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, map_map_of_string=None, map_of_enum_string=None, direct_map=None, indirect_map=None): # noqa: E501 additional_properties_type = None
"""MapTest - a model defined in OpenAPI""" # noqa: E501
self._map_map_of_string = None discriminator = None
self._map_of_enum_string = None
self._direct_map = None
self._indirect_map = None
self.discriminator = None
if map_map_of_string is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.map_map_of_string = ( """MapTest - a model defined in OpenAPI
map_map_of_string
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
map_map_of_string ({str: ({str: (str,)},)}): [optional] # noqa: E501
map_of_enum_string ({str: (str,)}): [optional] # noqa: E501
direct_map ({str: (bool,)}): [optional] # noqa: E501
indirect_map (StringBooleanMap): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if map_of_enum_string is not None: elif self.additional_properties_type is not None:
self.map_of_enum_string = ( required_types_mixed = self.additional_properties_type
map_of_enum_string
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if direct_map is not None: raise ApiTypeError(
self.direct_map = ( error_msg,
direct_map path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if indirect_map is not None:
self.indirect_map = ( if self._check_type:
indirect_map value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def map_map_of_string(self): def map_map_of_string(self):
"""Gets the map_map_of_string of this MapTest. # noqa: E501 """Gets the map_map_of_string of this MapTest. # noqa: E501
Returns:
:return: The map_map_of_string of this MapTest. # noqa: E501 ({str: ({str: (str,)},)}): The map_map_of_string of this MapTest. # noqa: E501
:rtype: dict(str, dict(str, str))
""" """
return self._map_map_of_string return self.__get_item('map_map_of_string')
@map_map_of_string.setter @map_map_of_string.setter
def map_map_of_string(self, map_map_of_string): # noqa: E501 def map_map_of_string(self, value):
"""Sets the map_map_of_string of this MapTest. """Sets the map_map_of_string of this MapTest. # noqa: E501
:param map_map_of_string: The map_map_of_string of this MapTest. # noqa: E501
:type: dict(str, dict(str, str))
""" """
return self.__set_item('map_map_of_string', value)
self._map_map_of_string = (
map_map_of_string
)
@property @property
def map_of_enum_string(self): def map_of_enum_string(self):
"""Gets the map_of_enum_string of this MapTest. # noqa: E501 """Gets the map_of_enum_string of this MapTest. # noqa: E501
Returns:
:return: The map_of_enum_string of this MapTest. # noqa: E501 ({str: (str,)}): The map_of_enum_string of this MapTest. # noqa: E501
:rtype: dict(str, str)
""" """
return self._map_of_enum_string return self.__get_item('map_of_enum_string')
@map_of_enum_string.setter @map_of_enum_string.setter
def map_of_enum_string(self, map_of_enum_string): # noqa: E501 def map_of_enum_string(self, value):
"""Sets the map_of_enum_string of this MapTest. """Sets the map_of_enum_string of this MapTest. # noqa: E501
:param map_of_enum_string: The map_of_enum_string of this MapTest. # noqa: E501
:type: dict(str, str)
""" """
check_allowed_values( return self.__set_item('map_of_enum_string', value)
self.allowed_values,
('map_of_enum_string',),
map_of_enum_string,
self.validations
)
self._map_of_enum_string = (
map_of_enum_string
)
@property @property
def direct_map(self): def direct_map(self):
"""Gets the direct_map of this MapTest. # noqa: E501 """Gets the direct_map of this MapTest. # noqa: E501
Returns:
:return: The direct_map of this MapTest. # noqa: E501 ({str: (bool,)}): The direct_map of this MapTest. # noqa: E501
:rtype: dict(str, bool)
""" """
return self._direct_map return self.__get_item('direct_map')
@direct_map.setter @direct_map.setter
def direct_map(self, direct_map): # noqa: E501 def direct_map(self, value):
"""Sets the direct_map of this MapTest. """Sets the direct_map of this MapTest. # noqa: E501
:param direct_map: The direct_map of this MapTest. # noqa: E501
:type: dict(str, bool)
""" """
return self.__set_item('direct_map', value)
self._direct_map = (
direct_map
)
@property @property
def indirect_map(self): def indirect_map(self):
"""Gets the indirect_map of this MapTest. # noqa: E501 """Gets the indirect_map of this MapTest. # noqa: E501
Returns:
:return: The indirect_map of this MapTest. # noqa: E501 (StringBooleanMap): The indirect_map of this MapTest. # noqa: E501
:rtype: StringBooleanMap
""" """
return self._indirect_map return self.__get_item('indirect_map')
@indirect_map.setter @indirect_map.setter
def indirect_map(self, indirect_map): # noqa: E501 def indirect_map(self, value):
"""Sets the indirect_map of this MapTest. """Sets the indirect_map of this MapTest. # noqa: E501
:param indirect_map: The indirect_map of this MapTest. # noqa: E501
:type: StringBooleanMap
""" """
return self.__set_item('indirect_map', value)
self._indirect_map = (
indirect_map
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -233,7 +271,22 @@ class MapTest(ModelNormal):
if not isinstance(other, MapTest): if not isinstance(other, MapTest):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.animal import Animal
class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal): class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal):
@@ -46,6 +61,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -58,127 +75,166 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal):
} }
openapi_types = { openapi_types = {
'uuid': 'str', 'uuid': (str,), # noqa: E501
'date_time': 'datetime', 'date_time': (datetime,), # noqa: E501
'map': 'dict(str, Animal)' 'map': ({str: (Animal,)},), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, uuid=None, date_time=None, map=None): # noqa: E501 additional_properties_type = None
"""MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI""" # noqa: E501
self._uuid = None discriminator = None
self._date_time = None
self._map = None
self.discriminator = None
if uuid is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.uuid = ( """MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI
uuid
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
uuid (str): [optional] # noqa: E501
date_time (datetime): [optional] # noqa: E501
map ({str: (Animal,)}): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if date_time is not None: elif self.additional_properties_type is not None:
self.date_time = ( required_types_mixed = self.additional_properties_type
date_time
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if map is not None: raise ApiTypeError(
self.map = ( error_msg,
map path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def uuid(self): def uuid(self):
"""Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 """Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
Returns:
:return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 (str): The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:rtype: str
""" """
return self._uuid return self.__get_item('uuid')
@uuid.setter @uuid.setter
def uuid(self, uuid): # noqa: E501 def uuid(self, value):
"""Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. """Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:type: str
""" """
return self.__set_item('uuid', value)
self._uuid = (
uuid
)
@property @property
def date_time(self): def date_time(self):
"""Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 """Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
Returns:
:return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 (datetime): The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:rtype: datetime
""" """
return self._date_time return self.__get_item('date_time')
@date_time.setter @date_time.setter
def date_time(self, date_time): # noqa: E501 def date_time(self, value):
"""Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. """Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:type: datetime
""" """
return self.__set_item('date_time', value)
self._date_time = (
date_time
)
@property @property
def map(self): def map(self):
"""Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 """Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
Returns:
:return: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501 ({str: (Animal,)}): The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:rtype: dict(str, Animal)
""" """
return self._map return self.__get_item('map')
@map.setter @map.setter
def map(self, map): # noqa: E501 def map(self, value):
"""Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. """Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. # noqa: E501
:type: dict(str, Animal)
""" """
return self.__set_item('map', value)
self._map = (
map
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -193,7 +249,22 @@ class MixedPropertiesAndAdditionalPropertiesClass(ModelNormal):
if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Model200Response(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,98 +73,149 @@ class Model200Response(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'int', 'name': (int,), # noqa: E501
'_class': 'str' '_class': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None, _class=None): # noqa: E501 additional_properties_type = None
"""Model200Response - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self.__class = None
self.discriminator = None
if name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.name = ( """Model200Response - a model defined in OpenAPI
name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
name (int): [optional] # noqa: E501
_class (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if _class is not None: elif self.additional_properties_type is not None:
self._class = ( required_types_mixed = self.additional_properties_type
_class
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this Model200Response. # noqa: E501 """Gets the name of this Model200Response. # noqa: E501
Returns:
:return: The name of this Model200Response. # noqa: E501 (int): The name of this Model200Response. # noqa: E501
:rtype: int
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this Model200Response. """Sets the name of this Model200Response. # noqa: E501
:param name: The name of this Model200Response. # noqa: E501
:type: int
""" """
return self.__set_item('name', value)
self._name = (
name
)
@property @property
def _class(self): def _class(self):
"""Gets the _class of this Model200Response. # noqa: E501 """Gets the _class of this Model200Response. # noqa: E501
Returns:
:return: The _class of this Model200Response. # noqa: E501 (str): The _class of this Model200Response. # noqa: E501
:rtype: str
""" """
return self.__class return self.__get_item('_class')
@_class.setter @_class.setter
def _class(self, _class): # noqa: E501 def _class(self, value):
"""Sets the _class of this Model200Response. """Sets the _class of this Model200Response. # noqa: E501
:param _class: The _class of this Model200Response. # noqa: E501
:type: str
""" """
return self.__set_item('_class', value)
self.__class = (
_class
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -163,7 +230,22 @@ class Model200Response(ModelNormal):
if not isinstance(other, Model200Response): if not isinstance(other, Model200Response):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ModelReturn(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class ModelReturn(ModelNormal):
} }
openapi_types = { openapi_types = {
'_return': 'int' '_return': (int,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, _return=None): # noqa: E501 additional_properties_type = None
"""ModelReturn - a model defined in OpenAPI""" # noqa: E501
self.__return = None discriminator = None
self.discriminator = None
if _return is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self._return = ( """ModelReturn - a model defined in OpenAPI
_return
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_return (int): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def _return(self): def _return(self):
"""Gets the _return of this ModelReturn. # noqa: E501 """Gets the _return of this ModelReturn. # noqa: E501
Returns:
:return: The _return of this ModelReturn. # noqa: E501 (int): The _return of this ModelReturn. # noqa: E501
:rtype: int
""" """
return self.__return return self.__get_item('_return')
@_return.setter @_return.setter
def _return(self, _return): # noqa: E501 def _return(self, value):
"""Sets the _return of this ModelReturn. """Sets the _return of this ModelReturn. # noqa: E501
:param _return: The _return of this ModelReturn. # noqa: E501
:type: int
""" """
return self.__set_item('_return', value)
self.__return = (
_return
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class ModelReturn(ModelNormal):
if not isinstance(other, ModelReturn): if not isinstance(other, ModelReturn):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Name(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -59,155 +75,185 @@ class Name(ModelNormal):
} }
openapi_types = { openapi_types = {
'name': 'int', 'name': (int,), # noqa: E501
'snake_case': 'int', 'snake_case': (int,), # noqa: E501
'_property': 'str', '_property': (str,), # noqa: E501
'_123_number': 'int' '_123_number': (int,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, name=None, snake_case=None, _property=None, _123_number=None): # noqa: E501 additional_properties_type = None
"""Name - a model defined in OpenAPI""" # noqa: E501
self._name = None discriminator = None
self._snake_case = None
self.__property = None
self.__123_number = None
self.discriminator = None
self.name = name def __init__(self, name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
if snake_case is not None: """Name - a model defined in OpenAPI
self.snake_case = (
snake_case Args:
name (int):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
snake_case (int): [optional] # noqa: E501
_property (str): [optional] # noqa: E501
_123_number (int): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('name', name)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if _property is not None: elif self.additional_properties_type is not None:
self._property = ( required_types_mixed = self.additional_properties_type
_property
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if _123_number is not None: raise ApiTypeError(
self._123_number = ( error_msg,
_123_number path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def name(self): def name(self):
"""Gets the name of this Name. # noqa: E501 """Gets the name of this Name. # noqa: E501
Returns:
:return: The name of this Name. # noqa: E501 (int): The name of this Name. # noqa: E501
:rtype: int
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this Name. """Sets the name of this Name. # noqa: E501
:param name: The name of this Name. # noqa: E501
:type: int
""" """
if name is None: return self.__set_item('name', value)
raise ApiValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = (
name
)
@property @property
def snake_case(self): def snake_case(self):
"""Gets the snake_case of this Name. # noqa: E501 """Gets the snake_case of this Name. # noqa: E501
Returns:
:return: The snake_case of this Name. # noqa: E501 (int): The snake_case of this Name. # noqa: E501
:rtype: int
""" """
return self._snake_case return self.__get_item('snake_case')
@snake_case.setter @snake_case.setter
def snake_case(self, snake_case): # noqa: E501 def snake_case(self, value):
"""Sets the snake_case of this Name. """Sets the snake_case of this Name. # noqa: E501
:param snake_case: The snake_case of this Name. # noqa: E501
:type: int
""" """
return self.__set_item('snake_case', value)
self._snake_case = (
snake_case
)
@property @property
def _property(self): def _property(self):
"""Gets the _property of this Name. # noqa: E501 """Gets the _property of this Name. # noqa: E501
Returns:
:return: The _property of this Name. # noqa: E501 (str): The _property of this Name. # noqa: E501
:rtype: str
""" """
return self.__property return self.__get_item('_property')
@_property.setter @_property.setter
def _property(self, _property): # noqa: E501 def _property(self, value):
"""Sets the _property of this Name. """Sets the _property of this Name. # noqa: E501
:param _property: The _property of this Name. # noqa: E501
:type: str
""" """
return self.__set_item('_property', value)
self.__property = (
_property
)
@property @property
def _123_number(self): def _123_number(self):
"""Gets the _123_number of this Name. # noqa: E501 """Gets the _123_number of this Name. # noqa: E501
Returns:
:return: The _123_number of this Name. # noqa: E501 (int): The _123_number of this Name. # noqa: E501
:rtype: int
""" """
return self.__123_number return self.__get_item('_123_number')
@_123_number.setter @_123_number.setter
def _123_number(self, _123_number): # noqa: E501 def _123_number(self, value):
"""Sets the _123_number of this Name. """Sets the _123_number of this Name. # noqa: E501
:param _123_number: The _123_number of this Name. # noqa: E501
:type: int
""" """
return self.__set_item('_123_number', value)
self.__123_number = (
_123_number
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -222,7 +268,22 @@ class Name(ModelNormal):
if not isinstance(other, Name): if not isinstance(other, Name):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class NumberOnly(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class NumberOnly(ModelNormal):
} }
openapi_types = { openapi_types = {
'just_number': 'float' 'just_number': (float,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, just_number=None): # noqa: E501 additional_properties_type = None
"""NumberOnly - a model defined in OpenAPI""" # noqa: E501
self._just_number = None discriminator = None
self.discriminator = None
if just_number is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.just_number = ( """NumberOnly - a model defined in OpenAPI
just_number
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
just_number (float): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def just_number(self): def just_number(self):
"""Gets the just_number of this NumberOnly. # noqa: E501 """Gets the just_number of this NumberOnly. # noqa: E501
Returns:
:return: The just_number of this NumberOnly. # noqa: E501 (float): The just_number of this NumberOnly. # noqa: E501
:rtype: float
""" """
return self._just_number return self.__get_item('just_number')
@just_number.setter @just_number.setter
def just_number(self, just_number): # noqa: E501 def just_number(self, value):
"""Sets the just_number of this NumberOnly. """Sets the just_number of this NumberOnly. # noqa: E501
:param just_number: The just_number of this NumberOnly. # noqa: E501
:type: float
""" """
return self.__set_item('just_number', value)
self._just_number = (
just_number
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class NumberOnly(ModelNormal):
if not isinstance(other, NumberOnly): if not isinstance(other, NumberOnly):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,13 +60,15 @@ class Order(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('status',): { ('status',): {
'PLACED': "placed", 'PLACED': "placed",
'APPROVED': "approved", 'APPROVED': "approved",
'DELIVERED': "delivered" 'DELIVERED': "delivered",
}, },
} }
@@ -66,222 +82,219 @@ class Order(ModelNormal):
} }
openapi_types = { openapi_types = {
'id': 'int', 'id': (int,), # noqa: E501
'pet_id': 'int', 'pet_id': (int,), # noqa: E501
'quantity': 'int', 'quantity': (int,), # noqa: E501
'ship_date': 'datetime', 'ship_date': (datetime,), # noqa: E501
'status': 'str', 'status': (str,), # noqa: E501
'complete': 'bool' 'complete': (bool,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 additional_properties_type = None
"""Order - a model defined in OpenAPI""" # noqa: E501
self._id = None discriminator = None
self._pet_id = None
self._quantity = None
self._ship_date = None
self._status = None
self._complete = None
self.discriminator = None
if id is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.id = ( """Order - a model defined in OpenAPI
id
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (int): [optional] # noqa: E501
pet_id (int): [optional] # noqa: E501
quantity (int): [optional] # noqa: E501
ship_date (datetime): [optional] # noqa: E501
status (str): Order Status. [optional] # noqa: E501
complete (bool): [optional] if omitted the server will use the default value of False # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if pet_id is not None: elif self.additional_properties_type is not None:
self.pet_id = ( required_types_mixed = self.additional_properties_type
pet_id
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if quantity is not None: raise ApiTypeError(
self.quantity = ( error_msg,
quantity path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if ship_date is not None:
self.ship_date = ( if self._check_type:
ship_date value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if status is not None: if (name,) in self.validations:
self.status = ( check_validations(
status self.validations,
) (name,),
if complete is not None: value
self.complete = (
complete
) )
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def id(self): def id(self):
"""Gets the id of this Order. # noqa: E501 """Gets the id of this Order. # noqa: E501
Returns:
:return: The id of this Order. # noqa: E501 (int): The id of this Order. # noqa: E501
:rtype: int
""" """
return self._id return self.__get_item('id')
@id.setter @id.setter
def id(self, id): # noqa: E501 def id(self, value):
"""Sets the id of this Order. """Sets the id of this Order. # noqa: E501
:param id: The id of this Order. # noqa: E501
:type: int
""" """
return self.__set_item('id', value)
self._id = (
id
)
@property @property
def pet_id(self): def pet_id(self):
"""Gets the pet_id of this Order. # noqa: E501 """Gets the pet_id of this Order. # noqa: E501
Returns:
:return: The pet_id of this Order. # noqa: E501 (int): The pet_id of this Order. # noqa: E501
:rtype: int
""" """
return self._pet_id return self.__get_item('pet_id')
@pet_id.setter @pet_id.setter
def pet_id(self, pet_id): # noqa: E501 def pet_id(self, value):
"""Sets the pet_id of this Order. """Sets the pet_id of this Order. # noqa: E501
:param pet_id: The pet_id of this Order. # noqa: E501
:type: int
""" """
return self.__set_item('pet_id', value)
self._pet_id = (
pet_id
)
@property @property
def quantity(self): def quantity(self):
"""Gets the quantity of this Order. # noqa: E501 """Gets the quantity of this Order. # noqa: E501
Returns:
:return: The quantity of this Order. # noqa: E501 (int): The quantity of this Order. # noqa: E501
:rtype: int
""" """
return self._quantity return self.__get_item('quantity')
@quantity.setter @quantity.setter
def quantity(self, quantity): # noqa: E501 def quantity(self, value):
"""Sets the quantity of this Order. """Sets the quantity of this Order. # noqa: E501
:param quantity: The quantity of this Order. # noqa: E501
:type: int
""" """
return self.__set_item('quantity', value)
self._quantity = (
quantity
)
@property @property
def ship_date(self): def ship_date(self):
"""Gets the ship_date of this Order. # noqa: E501 """Gets the ship_date of this Order. # noqa: E501
Returns:
:return: The ship_date of this Order. # noqa: E501 (datetime): The ship_date of this Order. # noqa: E501
:rtype: datetime
""" """
return self._ship_date return self.__get_item('ship_date')
@ship_date.setter @ship_date.setter
def ship_date(self, ship_date): # noqa: E501 def ship_date(self, value):
"""Sets the ship_date of this Order. """Sets the ship_date of this Order. # noqa: E501
:param ship_date: The ship_date of this Order. # noqa: E501
:type: datetime
""" """
return self.__set_item('ship_date', value)
self._ship_date = (
ship_date
)
@property @property
def status(self): def status(self):
"""Gets the status of this Order. # noqa: E501 """Gets the status of this Order. # noqa: E501
Order Status # noqa: E501 Order Status # noqa: E501
:return: The status of this Order. # noqa: E501 Returns:
:rtype: str (str): The status of this Order. # noqa: E501
""" """
return self._status return self.__get_item('status')
@status.setter @status.setter
def status(self, status): # noqa: E501 def status(self, value):
"""Sets the status of this Order. """Sets the status of this Order. # noqa: E501
Order Status # noqa: E501 Order Status # noqa: E501
:param status: The status of this Order. # noqa: E501
:type: str
""" """
check_allowed_values( return self.__set_item('status', value)
self.allowed_values,
('status',),
status,
self.validations
)
self._status = (
status
)
@property @property
def complete(self): def complete(self):
"""Gets the complete of this Order. # noqa: E501 """Gets the complete of this Order. # noqa: E501
Returns:
:return: The complete of this Order. # noqa: E501 (bool): The complete of this Order. # noqa: E501
:rtype: bool
""" """
return self._complete return self.__get_item('complete')
@complete.setter @complete.setter
def complete(self, complete): # noqa: E501 def complete(self, value):
"""Sets the complete of this Order. """Sets the complete of this Order. # noqa: E501
:param complete: The complete of this Order. # noqa: E501
:type: bool
""" """
return self.__set_item('complete', value)
self._complete = (
complete
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -296,7 +309,22 @@ class Order(ModelNormal):
if not isinstance(other, Order): if not isinstance(other, Order):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,28 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.outer_number import OuterNumber
class OuterComposite(ModelNormal): class OuterComposite(ModelNormal):
@@ -46,6 +61,8 @@ class OuterComposite(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -58,127 +75,166 @@ class OuterComposite(ModelNormal):
} }
openapi_types = { openapi_types = {
'my_number': 'OuterNumber', 'my_number': (OuterNumber,), # noqa: E501
'my_string': 'str', 'my_string': (str,), # noqa: E501
'my_boolean': 'bool' 'my_boolean': (bool,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, my_number=None, my_string=None, my_boolean=None): # noqa: E501 additional_properties_type = None
"""OuterComposite - a model defined in OpenAPI""" # noqa: E501
self._my_number = None discriminator = None
self._my_string = None
self._my_boolean = None
self.discriminator = None
if my_number is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.my_number = ( """OuterComposite - a model defined in OpenAPI
my_number
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
my_number (OuterNumber): [optional] # noqa: E501
my_string (str): [optional] # noqa: E501
my_boolean (bool): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if my_string is not None: elif self.additional_properties_type is not None:
self.my_string = ( required_types_mixed = self.additional_properties_type
my_string
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
if my_boolean is not None: raise ApiTypeError(
self.my_boolean = ( error_msg,
my_boolean path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
) )
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def my_number(self): def my_number(self):
"""Gets the my_number of this OuterComposite. # noqa: E501 """Gets the my_number of this OuterComposite. # noqa: E501
Returns:
:return: The my_number of this OuterComposite. # noqa: E501 (OuterNumber): The my_number of this OuterComposite. # noqa: E501
:rtype: OuterNumber
""" """
return self._my_number return self.__get_item('my_number')
@my_number.setter @my_number.setter
def my_number(self, my_number): # noqa: E501 def my_number(self, value):
"""Sets the my_number of this OuterComposite. """Sets the my_number of this OuterComposite. # noqa: E501
:param my_number: The my_number of this OuterComposite. # noqa: E501
:type: OuterNumber
""" """
return self.__set_item('my_number', value)
self._my_number = (
my_number
)
@property @property
def my_string(self): def my_string(self):
"""Gets the my_string of this OuterComposite. # noqa: E501 """Gets the my_string of this OuterComposite. # noqa: E501
Returns:
:return: The my_string of this OuterComposite. # noqa: E501 (str): The my_string of this OuterComposite. # noqa: E501
:rtype: str
""" """
return self._my_string return self.__get_item('my_string')
@my_string.setter @my_string.setter
def my_string(self, my_string): # noqa: E501 def my_string(self, value):
"""Sets the my_string of this OuterComposite. """Sets the my_string of this OuterComposite. # noqa: E501
:param my_string: The my_string of this OuterComposite. # noqa: E501
:type: str
""" """
return self.__set_item('my_string', value)
self._my_string = (
my_string
)
@property @property
def my_boolean(self): def my_boolean(self):
"""Gets the my_boolean of this OuterComposite. # noqa: E501 """Gets the my_boolean of this OuterComposite. # noqa: E501
Returns:
:return: The my_boolean of this OuterComposite. # noqa: E501 (bool): The my_boolean of this OuterComposite. # noqa: E501
:rtype: bool
""" """
return self._my_boolean return self.__get_item('my_boolean')
@my_boolean.setter @my_boolean.setter
def my_boolean(self, my_boolean): # noqa: E501 def my_boolean(self, value):
"""Sets the my_boolean of this OuterComposite. """Sets the my_boolean of this OuterComposite. # noqa: E501
:param my_boolean: The my_boolean of this OuterComposite. # noqa: E501
:type: bool
""" """
return self.__set_item('my_boolean', value)
self._my_boolean = (
my_boolean
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -193,7 +249,22 @@ class OuterComposite(ModelNormal):
if not isinstance(other, OuterComposite): if not isinstance(other, OuterComposite):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -42,65 +56,147 @@ class OuterEnum(ModelSimple):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('value',): { ('value',): {
'PLACED': "placed", 'PLACED': "placed",
'APPROVED': "approved", 'APPROVED': "approved",
'DELIVERED': "delivered" 'DELIVERED': "delivered",
}, },
} }
openapi_types = { openapi_types = {
'value': 'str' 'value': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, value=None): # noqa: E501 additional_properties_type = None
"""OuterEnum - a model defined in OpenAPI""" # noqa: E501
self._value = None discriminator = None
self.discriminator = None
self.value = value def __init__(self, value, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
"""OuterEnum - a model defined in OpenAPI
Args:
value (str):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('value', value)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
)
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def value(self): def value(self):
"""Gets the value of this OuterEnum. # noqa: E501 """Gets the value of this OuterEnum. # noqa: E501
Returns:
:return: The value of this OuterEnum. # noqa: E501 (str): The value of this OuterEnum. # noqa: E501
:rtype: str
""" """
return self._value return self.__get_item('value')
@value.setter @value.setter
def value(self, value): # noqa: E501 def value(self, value):
"""Sets the value of this OuterEnum. """Sets the value of this OuterEnum. # noqa: E501
:param value: The value of this OuterEnum. # noqa: E501
:type: str
""" """
if value is None: return self.__set_item('value', value)
raise ApiValueError("Invalid value for `value`, must not be `None`") # noqa: E501
check_allowed_values(
self.allowed_values,
('value',),
value,
self.validations
)
self._value = (
value
)
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
return str(self._value) return str(self.value)
def __repr__(self): def __repr__(self):
"""For `print` and `pprint`""" """For `print` and `pprint`"""
@@ -111,7 +207,19 @@ class OuterEnum(ModelSimple):
if not isinstance(other, OuterEnum): if not isinstance(other, OuterEnum):
return False return False
return self.__dict__ == other.__dict__ this_val = self._data_store['value']
that_val = other._data_store['value']
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -42,64 +56,146 @@ class OuterNumber(ModelSimple):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
} }
openapi_types = { openapi_types = {
'value': 'float' 'value': (float,), # noqa: E501
} }
validations = { validations = {
('value',): { ('value',): {
'inclusive_maximum': 2E+1, 'inclusive_maximum': 2E+1,
'inclusive_minimum': 1E+1, 'inclusive_minimum': 1E+1,
}, },
} }
def __init__(self, value=None): # noqa: E501 additional_properties_type = None
"""OuterNumber - a model defined in OpenAPI""" # noqa: E501
self._value = None discriminator = None
self.discriminator = None
self.value = value def __init__(self, value, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
"""OuterNumber - a model defined in OpenAPI
Args:
value (float):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('value', value)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
)
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def value(self): def value(self):
"""Gets the value of this OuterNumber. # noqa: E501 """Gets the value of this OuterNumber. # noqa: E501
Returns:
:return: The value of this OuterNumber. # noqa: E501 (float): The value of this OuterNumber. # noqa: E501
:rtype: float
""" """
return self._value return self.__get_item('value')
@value.setter @value.setter
def value(self, value): # noqa: E501 def value(self, value):
"""Sets the value of this OuterNumber. """Sets the value of this OuterNumber. # noqa: E501
:param value: The value of this OuterNumber. # noqa: E501
:type: float
""" """
if value is None: return self.__set_item('value', value)
raise ApiValueError("Invalid value for `value`, must not be `None`") # noqa: E501
check_validations(
self.validations,
('value',),
value
)
self._value = (
value
)
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
return str(self._value) return str(self.value)
def __repr__(self): def __repr__(self):
"""For `print` and `pprint`""" """For `print` and `pprint`"""
@@ -110,7 +206,19 @@ class OuterNumber(ModelSimple):
if not isinstance(other, OuterNumber): if not isinstance(other, OuterNumber):
return False return False
return self.__dict__ == other.__dict__ this_val = self._data_store['value']
that_val = other._data_store['value']
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if not six.PY3 and len(types) == 2 and unicode in types: # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,13 +15,29 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
from petstore_api.models.category import Category
from petstore_api.models.tag import Tag
class Pet(ModelNormal): class Pet(ModelNormal):
@@ -46,13 +62,15 @@ class Pet(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
('status',): { ('status',): {
'AVAILABLE': "available", 'AVAILABLE': "available",
'PENDING': "pending", 'PENDING': "pending",
'SOLD': "sold" 'SOLD': "sold",
}, },
} }
@@ -66,220 +84,222 @@ class Pet(ModelNormal):
} }
openapi_types = { openapi_types = {
'id': 'int', 'id': (int,), # noqa: E501
'category': 'Category', 'category': (Category,), # noqa: E501
'name': 'str', 'name': (str,), # noqa: E501
'photo_urls': 'list[str]', 'photo_urls': ([str],), # noqa: E501
'tags': 'list[Tag]', 'tags': ([Tag],), # noqa: E501
'status': 'str' 'status': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 additional_properties_type = None
"""Pet - a model defined in OpenAPI""" # noqa: E501
self._id = None discriminator = None
self._category = None
self._name = None
self._photo_urls = None
self._tags = None
self._status = None
self.discriminator = None
if id is not None: def __init__(self, name, photo_urls, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.id = ( """Pet - a model defined in OpenAPI
id
Args:
name (str):
photo_urls ([str]):
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (int): [optional] # noqa: E501
category (Category): [optional] # noqa: E501
tags ([Tag]): [optional] # noqa: E501
status (str): pet status in the store. [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('name', name)
self.__set_item('photo_urls', photo_urls)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if category is not None: elif self.additional_properties_type is not None:
self.category = ( required_types_mixed = self.additional_properties_type
category
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
self.name = name raise ApiTypeError(
self.photo_urls = photo_urls error_msg,
if tags is not None: path_to_item=path_to_item,
self.tags = ( valid_classes=(str,),
tags key_type=True
) )
if status is not None:
self.status = ( if self._check_type:
status value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
) )
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def id(self): def id(self):
"""Gets the id of this Pet. # noqa: E501 """Gets the id of this Pet. # noqa: E501
Returns:
:return: The id of this Pet. # noqa: E501 (int): The id of this Pet. # noqa: E501
:rtype: int
""" """
return self._id return self.__get_item('id')
@id.setter @id.setter
def id(self, id): # noqa: E501 def id(self, value):
"""Sets the id of this Pet. """Sets the id of this Pet. # noqa: E501
:param id: The id of this Pet. # noqa: E501
:type: int
""" """
return self.__set_item('id', value)
self._id = (
id
)
@property @property
def category(self): def category(self):
"""Gets the category of this Pet. # noqa: E501 """Gets the category of this Pet. # noqa: E501
Returns:
:return: The category of this Pet. # noqa: E501 (Category): The category of this Pet. # noqa: E501
:rtype: Category
""" """
return self._category return self.__get_item('category')
@category.setter @category.setter
def category(self, category): # noqa: E501 def category(self, value):
"""Sets the category of this Pet. """Sets the category of this Pet. # noqa: E501
:param category: The category of this Pet. # noqa: E501
:type: Category
""" """
return self.__set_item('category', value)
self._category = (
category
)
@property @property
def name(self): def name(self):
"""Gets the name of this Pet. # noqa: E501 """Gets the name of this Pet. # noqa: E501
Returns:
:return: The name of this Pet. # noqa: E501 (str): The name of this Pet. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this Pet. """Sets the name of this Pet. # noqa: E501
:param name: The name of this Pet. # noqa: E501
:type: str
""" """
if name is None: return self.__set_item('name', value)
raise ApiValueError("Invalid value for `name`, must not be `None`") # noqa: E501
self._name = (
name
)
@property @property
def photo_urls(self): def photo_urls(self):
"""Gets the photo_urls of this Pet. # noqa: E501 """Gets the photo_urls of this Pet. # noqa: E501
Returns:
:return: The photo_urls of this Pet. # noqa: E501 ([str]): The photo_urls of this Pet. # noqa: E501
:rtype: list[str]
""" """
return self._photo_urls return self.__get_item('photo_urls')
@photo_urls.setter @photo_urls.setter
def photo_urls(self, photo_urls): # noqa: E501 def photo_urls(self, value):
"""Sets the photo_urls of this Pet. """Sets the photo_urls of this Pet. # noqa: E501
:param photo_urls: The photo_urls of this Pet. # noqa: E501
:type: list[str]
""" """
if photo_urls is None: return self.__set_item('photo_urls', value)
raise ApiValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501
self._photo_urls = (
photo_urls
)
@property @property
def tags(self): def tags(self):
"""Gets the tags of this Pet. # noqa: E501 """Gets the tags of this Pet. # noqa: E501
Returns:
:return: The tags of this Pet. # noqa: E501 ([Tag]): The tags of this Pet. # noqa: E501
:rtype: list[Tag]
""" """
return self._tags return self.__get_item('tags')
@tags.setter @tags.setter
def tags(self, tags): # noqa: E501 def tags(self, value):
"""Sets the tags of this Pet. """Sets the tags of this Pet. # noqa: E501
:param tags: The tags of this Pet. # noqa: E501
:type: list[Tag]
""" """
return self.__set_item('tags', value)
self._tags = (
tags
)
@property @property
def status(self): def status(self):
"""Gets the status of this Pet. # noqa: E501 """Gets the status of this Pet. # noqa: E501
pet status in the store # noqa: E501 pet status in the store # noqa: E501
:return: The status of this Pet. # noqa: E501 Returns:
:rtype: str (str): The status of this Pet. # noqa: E501
""" """
return self._status return self.__get_item('status')
@status.setter @status.setter
def status(self, status): # noqa: E501 def status(self, value):
"""Sets the status of this Pet. """Sets the status of this Pet. # noqa: E501
pet status in the store # noqa: E501 pet status in the store # noqa: E501
:param status: The status of this Pet. # noqa: E501
:type: str
""" """
check_allowed_values( return self.__set_item('status', value)
self.allowed_values,
('status',),
status,
self.validations
)
self._status = (
status
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -294,7 +314,22 @@ class Pet(ModelNormal):
if not isinstance(other, Pet): if not isinstance(other, Pet):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class ReadOnlyFirst(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,98 +73,149 @@ class ReadOnlyFirst(ModelNormal):
} }
openapi_types = { openapi_types = {
'bar': 'str', 'bar': (str,), # noqa: E501
'baz': 'str' 'baz': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, bar=None, baz=None): # noqa: E501 additional_properties_type = None
"""ReadOnlyFirst - a model defined in OpenAPI""" # noqa: E501
self._bar = None discriminator = None
self._baz = None
self.discriminator = None
if bar is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.bar = ( """ReadOnlyFirst - a model defined in OpenAPI
bar
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
bar (str): [optional] # noqa: E501
baz (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if baz is not None: elif self.additional_properties_type is not None:
self.baz = ( required_types_mixed = self.additional_properties_type
baz
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def bar(self): def bar(self):
"""Gets the bar of this ReadOnlyFirst. # noqa: E501 """Gets the bar of this ReadOnlyFirst. # noqa: E501
Returns:
:return: The bar of this ReadOnlyFirst. # noqa: E501 (str): The bar of this ReadOnlyFirst. # noqa: E501
:rtype: str
""" """
return self._bar return self.__get_item('bar')
@bar.setter @bar.setter
def bar(self, bar): # noqa: E501 def bar(self, value):
"""Sets the bar of this ReadOnlyFirst. """Sets the bar of this ReadOnlyFirst. # noqa: E501
:param bar: The bar of this ReadOnlyFirst. # noqa: E501
:type: str
""" """
return self.__set_item('bar', value)
self._bar = (
bar
)
@property @property
def baz(self): def baz(self):
"""Gets the baz of this ReadOnlyFirst. # noqa: E501 """Gets the baz of this ReadOnlyFirst. # noqa: E501
Returns:
:return: The baz of this ReadOnlyFirst. # noqa: E501 (str): The baz of this ReadOnlyFirst. # noqa: E501
:rtype: str
""" """
return self._baz return self.__get_item('baz')
@baz.setter @baz.setter
def baz(self, baz): # noqa: E501 def baz(self, value):
"""Sets the baz of this ReadOnlyFirst. """Sets the baz of this ReadOnlyFirst. # noqa: E501
:param baz: The baz of this ReadOnlyFirst. # noqa: E501
:type: str
""" """
return self.__set_item('baz', value)
self._baz = (
baz
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -163,7 +230,22 @@ class ReadOnlyFirst(ModelNormal):
if not isinstance(other, ReadOnlyFirst): if not isinstance(other, ReadOnlyFirst):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class SpecialModelName(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -56,69 +72,132 @@ class SpecialModelName(ModelNormal):
} }
openapi_types = { openapi_types = {
'special_property_name': 'int' 'special_property_name': (int,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, special_property_name=None): # noqa: E501 additional_properties_type = None
"""SpecialModelName - a model defined in OpenAPI""" # noqa: E501
self._special_property_name = None discriminator = None
self.discriminator = None
if special_property_name is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.special_property_name = ( """SpecialModelName - a model defined in OpenAPI
special_property_name
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
special_property_name (int): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def special_property_name(self): def special_property_name(self):
"""Gets the special_property_name of this SpecialModelName. # noqa: E501 """Gets the special_property_name of this SpecialModelName. # noqa: E501
Returns:
:return: The special_property_name of this SpecialModelName. # noqa: E501 (int): The special_property_name of this SpecialModelName. # noqa: E501
:rtype: int
""" """
return self._special_property_name return self.__get_item('special_property_name')
@special_property_name.setter @special_property_name.setter
def special_property_name(self, special_property_name): # noqa: E501 def special_property_name(self, value):
"""Sets the special_property_name of this SpecialModelName. """Sets the special_property_name of this SpecialModelName. # noqa: E501
:param special_property_name: The special_property_name of this SpecialModelName. # noqa: E501
:type: int
""" """
return self.__set_item('special_property_name', value)
self._special_property_name = (
special_property_name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -133,7 +212,22 @@ class SpecialModelName(ModelNormal):
if not isinstance(other, SpecialModelName): if not isinstance(other, SpecialModelName):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class StringBooleanMap(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -60,33 +76,110 @@ class StringBooleanMap(ModelNormal):
validations = { validations = {
} }
def __init__(self): # noqa: E501 additional_properties_type = (bool,) # noqa: E501
"""StringBooleanMap - a model defined in OpenAPI""" # noqa: E501
self.discriminator = None discriminator = None
def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
"""StringBooleanMap - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
)
elif self.additional_properties_type is not None:
required_types_mixed = self.additional_properties_type
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
)
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -101,7 +194,22 @@ class StringBooleanMap(ModelNormal):
if not isinstance(other, StringBooleanMap): if not isinstance(other, StringBooleanMap):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class Tag(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -57,98 +73,149 @@ class Tag(ModelNormal):
} }
openapi_types = { openapi_types = {
'id': 'int', 'id': (int,), # noqa: E501
'name': 'str' 'name': (str,), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, id=None, name=None): # noqa: E501 additional_properties_type = None
"""Tag - a model defined in OpenAPI""" # noqa: E501
self._id = None discriminator = None
self._name = None
self.discriminator = None
if id is not None: def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.id = ( """Tag - a model defined in OpenAPI
id
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
id (int): [optional] # noqa: E501
name (str): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if name is not None: elif self.additional_properties_type is not None:
self.name = ( required_types_mixed = self.additional_properties_type
name
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def id(self): def id(self):
"""Gets the id of this Tag. # noqa: E501 """Gets the id of this Tag. # noqa: E501
Returns:
:return: The id of this Tag. # noqa: E501 (int): The id of this Tag. # noqa: E501
:rtype: int
""" """
return self._id return self.__get_item('id')
@id.setter @id.setter
def id(self, id): # noqa: E501 def id(self, value):
"""Sets the id of this Tag. """Sets the id of this Tag. # noqa: E501
:param id: The id of this Tag. # noqa: E501
:type: int
""" """
return self.__set_item('id', value)
self._id = (
id
)
@property @property
def name(self): def name(self):
"""Gets the name of this Tag. # noqa: E501 """Gets the name of this Tag. # noqa: E501
Returns:
:return: The name of this Tag. # noqa: E501 (str): The name of this Tag. # noqa: E501
:rtype: str
""" """
return self._name return self.__get_item('name')
@name.setter @name.setter
def name(self, name): # noqa: E501 def name(self, value):
"""Sets the name of this Tag. """Sets the name of this Tag. # noqa: E501
:param name: The name of this Tag. # noqa: E501
:type: str
""" """
return self.__set_item('name', value)
self._name = (
name
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -163,7 +230,22 @@ class Tag(ModelNormal):
if not isinstance(other, Tag): if not isinstance(other, Tag):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

View File

@@ -15,12 +15,26 @@ import re # noqa: F401
import six # noqa: F401 import six # noqa: F401
from petstore_api.exceptions import ApiValueError # noqa: F401 from petstore_api.exceptions import ( # noqa: F401
ApiKeyError,
ApiTypeError,
ApiValueError,
)
from petstore_api.model_utils import ( # noqa: F401 from petstore_api.model_utils import ( # noqa: F401
ModelNormal, ModelNormal,
ModelSimple, ModelSimple,
check_allowed_values, check_allowed_values,
check_validations check_validations,
date,
datetime,
file_type,
get_simple_class,
int,
model_to_dict,
none_type,
str,
type_error_message,
validate_and_convert_types
) )
@@ -46,6 +60,8 @@ class TypeHolderDefault(ModelNormal):
that stores validations for max_length, min_length, max_items, that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex. inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
""" """
allowed_values = { allowed_values = {
@@ -62,238 +78,240 @@ class TypeHolderDefault(ModelNormal):
} }
openapi_types = { openapi_types = {
'string_item': 'str', 'string_item': (str,), # noqa: E501
'number_item': 'float', 'number_item': (float,), # noqa: E501
'integer_item': 'int', 'integer_item': (int,), # noqa: E501
'bool_item': 'bool', 'bool_item': (bool,), # noqa: E501
'date_item': 'date', 'date_item': (date,), # noqa: E501
'datetime_item': 'datetime', 'datetime_item': (datetime,), # noqa: E501
'array_item': 'list[int]' 'array_item': ([int],), # noqa: E501
} }
validations = { validations = {
} }
def __init__(self, string_item='what', number_item=1.234, integer_item=-2, bool_item=True, date_item=None, datetime_item=None, array_item=None): # noqa: E501 additional_properties_type = None
"""TypeHolderDefault - a model defined in OpenAPI""" # noqa: E501
self._string_item = None discriminator = None
self._number_item = None
self._integer_item = None
self._bool_item = None
self._date_item = None
self._datetime_item = None
self._array_item = None
self.discriminator = None
self.string_item = string_item def __init__(self, array_item, string_item='what', number_item=1.234, integer_item=-2, bool_item=True, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501
self.number_item = number_item """TypeHolderDefault - a model defined in OpenAPI
self.integer_item = integer_item
self.bool_item = bool_item Args:
if date_item is not None: array_item ([int]):
self.date_item = (
date_item Keyword Args:
string_item (str): defaults to 'what', must be one of ['what'] # noqa: E501
number_item (float): defaults to 1.234, must be one of [1.234] # noqa: E501
integer_item (int): defaults to -2, must be one of [-2] # noqa: E501
bool_item (bool): defaults to True, must be one of [True] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_from_server (bool): True if the data is from the server
False if the data is from the client (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
date_item (date): [optional] # noqa: E501
datetime_item (datetime): [optional] # noqa: E501
"""
self._data_store = {}
self._check_type = _check_type
self._from_server = _from_server
self._path_to_item = _path_to_item
self._configuration = _configuration
self.__set_item('string_item', string_item)
self.__set_item('number_item', number_item)
self.__set_item('integer_item', integer_item)
self.__set_item('bool_item', bool_item)
self.__set_item('array_item', array_item)
for var_name, var_value in six.iteritems(kwargs):
self.__set_item(var_name, var_value)
def __set_item(self, name, value):
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
if name in self.openapi_types:
required_types_mixed = self.openapi_types[name]
elif self.additional_properties_type is None:
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
path_to_item
) )
if datetime_item is not None: elif self.additional_properties_type is not None:
self.datetime_item = ( required_types_mixed = self.additional_properties_type
datetime_item
if get_simple_class(name) != str:
error_msg = type_error_message(
var_name=name,
var_value=name,
valid_classes=(str,),
key_type=True
) )
self.array_item = array_item raise ApiTypeError(
error_msg,
path_to_item=path_to_item,
valid_classes=(str,),
key_type=True
)
if self._check_type:
value = validate_and_convert_types(
value, required_types_mixed, path_to_item, self._from_server,
self._check_type, configuration=self._configuration)
if (name,) in self.allowed_values:
check_allowed_values(
self.allowed_values,
(name,),
value
)
if (name,) in self.validations:
check_validations(
self.validations,
(name,),
value
)
self._data_store[name] = value
def __get_item(self, name):
if name in self._data_store:
return self._data_store[name]
path_to_item = []
if self._path_to_item:
path_to_item.extend(self._path_to_item)
path_to_item.append(name)
raise ApiKeyError(
"{0} has no key '{1}'".format(type(self).__name__, name),
[name]
)
def __setitem__(self, name, value):
"""this allows us to set values with instance[field_name] = val"""
self.__set_item(name, value)
def __getitem__(self, name):
"""this allows us to get a value with val = instance[field_name]"""
return self.__get_item(name)
@property @property
def string_item(self): def string_item(self):
"""Gets the string_item of this TypeHolderDefault. # noqa: E501 """Gets the string_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The string_item of this TypeHolderDefault. # noqa: E501 (str): The string_item of this TypeHolderDefault. # noqa: E501
:rtype: str
""" """
return self._string_item return self.__get_item('string_item')
@string_item.setter @string_item.setter
def string_item(self, string_item): # noqa: E501 def string_item(self, value):
"""Sets the string_item of this TypeHolderDefault. """Sets the string_item of this TypeHolderDefault. # noqa: E501
:param string_item: The string_item of this TypeHolderDefault. # noqa: E501
:type: str
""" """
if string_item is None: return self.__set_item('string_item', value)
raise ApiValueError("Invalid value for `string_item`, must not be `None`") # noqa: E501
self._string_item = (
string_item
)
@property @property
def number_item(self): def number_item(self):
"""Gets the number_item of this TypeHolderDefault. # noqa: E501 """Gets the number_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The number_item of this TypeHolderDefault. # noqa: E501 (float): The number_item of this TypeHolderDefault. # noqa: E501
:rtype: float
""" """
return self._number_item return self.__get_item('number_item')
@number_item.setter @number_item.setter
def number_item(self, number_item): # noqa: E501 def number_item(self, value):
"""Sets the number_item of this TypeHolderDefault. """Sets the number_item of this TypeHolderDefault. # noqa: E501
:param number_item: The number_item of this TypeHolderDefault. # noqa: E501
:type: float
""" """
if number_item is None: return self.__set_item('number_item', value)
raise ApiValueError("Invalid value for `number_item`, must not be `None`") # noqa: E501
self._number_item = (
number_item
)
@property @property
def integer_item(self): def integer_item(self):
"""Gets the integer_item of this TypeHolderDefault. # noqa: E501 """Gets the integer_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The integer_item of this TypeHolderDefault. # noqa: E501 (int): The integer_item of this TypeHolderDefault. # noqa: E501
:rtype: int
""" """
return self._integer_item return self.__get_item('integer_item')
@integer_item.setter @integer_item.setter
def integer_item(self, integer_item): # noqa: E501 def integer_item(self, value):
"""Sets the integer_item of this TypeHolderDefault. """Sets the integer_item of this TypeHolderDefault. # noqa: E501
:param integer_item: The integer_item of this TypeHolderDefault. # noqa: E501
:type: int
""" """
if integer_item is None: return self.__set_item('integer_item', value)
raise ApiValueError("Invalid value for `integer_item`, must not be `None`") # noqa: E501
self._integer_item = (
integer_item
)
@property @property
def bool_item(self): def bool_item(self):
"""Gets the bool_item of this TypeHolderDefault. # noqa: E501 """Gets the bool_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The bool_item of this TypeHolderDefault. # noqa: E501 (bool): The bool_item of this TypeHolderDefault. # noqa: E501
:rtype: bool
""" """
return self._bool_item return self.__get_item('bool_item')
@bool_item.setter @bool_item.setter
def bool_item(self, bool_item): # noqa: E501 def bool_item(self, value):
"""Sets the bool_item of this TypeHolderDefault. """Sets the bool_item of this TypeHolderDefault. # noqa: E501
:param bool_item: The bool_item of this TypeHolderDefault. # noqa: E501
:type: bool
""" """
if bool_item is None: return self.__set_item('bool_item', value)
raise ApiValueError("Invalid value for `bool_item`, must not be `None`") # noqa: E501
self._bool_item = (
bool_item
)
@property @property
def date_item(self): def date_item(self):
"""Gets the date_item of this TypeHolderDefault. # noqa: E501 """Gets the date_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The date_item of this TypeHolderDefault. # noqa: E501 (date): The date_item of this TypeHolderDefault. # noqa: E501
:rtype: date
""" """
return self._date_item return self.__get_item('date_item')
@date_item.setter @date_item.setter
def date_item(self, date_item): # noqa: E501 def date_item(self, value):
"""Sets the date_item of this TypeHolderDefault. """Sets the date_item of this TypeHolderDefault. # noqa: E501
:param date_item: The date_item of this TypeHolderDefault. # noqa: E501
:type: date
""" """
return self.__set_item('date_item', value)
self._date_item = (
date_item
)
@property @property
def datetime_item(self): def datetime_item(self):
"""Gets the datetime_item of this TypeHolderDefault. # noqa: E501 """Gets the datetime_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The datetime_item of this TypeHolderDefault. # noqa: E501 (datetime): The datetime_item of this TypeHolderDefault. # noqa: E501
:rtype: datetime
""" """
return self._datetime_item return self.__get_item('datetime_item')
@datetime_item.setter @datetime_item.setter
def datetime_item(self, datetime_item): # noqa: E501 def datetime_item(self, value):
"""Sets the datetime_item of this TypeHolderDefault. """Sets the datetime_item of this TypeHolderDefault. # noqa: E501
:param datetime_item: The datetime_item of this TypeHolderDefault. # noqa: E501
:type: datetime
""" """
return self.__set_item('datetime_item', value)
self._datetime_item = (
datetime_item
)
@property @property
def array_item(self): def array_item(self):
"""Gets the array_item of this TypeHolderDefault. # noqa: E501 """Gets the array_item of this TypeHolderDefault. # noqa: E501
Returns:
:return: The array_item of this TypeHolderDefault. # noqa: E501 ([int]): The array_item of this TypeHolderDefault. # noqa: E501
:rtype: list[int]
""" """
return self._array_item return self.__get_item('array_item')
@array_item.setter @array_item.setter
def array_item(self, array_item): # noqa: E501 def array_item(self, value):
"""Sets the array_item of this TypeHolderDefault. """Sets the array_item of this TypeHolderDefault. # noqa: E501
:param array_item: The array_item of this TypeHolderDefault. # noqa: E501
:type: list[int]
""" """
if array_item is None: return self.__set_item('array_item', value)
raise ApiValueError("Invalid value for `array_item`, must not be `None`") # noqa: E501
self._array_item = (
array_item
)
def to_dict(self): def to_dict(self):
"""Returns the model properties as a dict""" """Returns the model properties as a dict"""
result = {} return model_to_dict(self, serialize=False)
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self): def to_str(self):
"""Returns the string representation of the model""" """Returns the string representation of the model"""
@@ -308,7 +326,22 @@ class TypeHolderDefault(ModelNormal):
if not isinstance(other, TypeHolderDefault): if not isinstance(other, TypeHolderDefault):
return False return False
return self.__dict__ == other.__dict__ if not set(self._data_store.keys()) == set(other._data_store.keys()):
return False
for _var_name, this_val in six.iteritems(self._data_store):
that_val = other._data_store[_var_name]
types = set()
types.add(this_val.__class__)
types.add(that_val.__class__)
vals_equal = this_val == that_val
if (not six.PY3 and
len(types) == 2 and unicode in types): # noqa: F821
vals_equal = (
this_val.encode('utf-8') == that_val.encode('utf-8')
)
if not vals_equal:
return False
return True
def __ne__(self, other): def __ne__(self, other):
"""Returns true if both objects are not equal""" """Returns true if both objects are not equal"""

Some files were not shown because too many files have changed in this diff Show More