forked from loafle/openapi-generator-original
[python] Renames python generators (#7965)
* python->python-legacy, python-experimental->python * test with openjdk8 * test with openjdk11 * comment out rm * move kotlin tests to circleci * move kotlin tests * move tests to circleci * fix circleci * rearrange test * move tests * use wrapper Co-authored-by: Justin Black <justin.a.black@gmail.com>
This commit is contained in:
parent
c08f14500e
commit
3bf8ca7484
@ -860,7 +860,7 @@ Here is a list of template creators:
|
||||
* PHP (Guzzle): @baartosz
|
||||
* PowerShell: @beatcracker
|
||||
* PowerShell (refactored in 5.0.0): @wing328
|
||||
* Python-experimental: @spacether
|
||||
* Python: @spacether
|
||||
* R: @ramnov
|
||||
* Ruby (Faraday): @meganemura @dkliban
|
||||
* Rust: @farcaller
|
||||
|
@ -1,7 +1,7 @@
|
||||
generatorName: python
|
||||
generatorName: python-legacy
|
||||
outputDir: samples/client/petstore/python-asyncio
|
||||
library: asyncio
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
templateDir: modules/openapi-generator/src/main/resources/python-legacy
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
||||
|
@ -1,7 +0,0 @@
|
||||
generatorName: python-experimental
|
||||
outputDir: samples/client/petstore/python-experimental
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
||||
disallowAdditionalPropertiesIfNotPresent: "true"
|
||||
packageName: petstore_api
|
@ -1,7 +0,0 @@
|
||||
generatorName: python-experimental
|
||||
outputDir: samples/openapi3/client/petstore/python-experimental
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
||||
recursionLimit: "1234"
|
@ -1,5 +1,5 @@
|
||||
generatorName: python-experimental
|
||||
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python-experimental/
|
||||
generatorName: python
|
||||
outputDir: samples/openapi3/client/extensions/x-auth-id-alias/python/
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
@ -1,5 +1,5 @@
|
||||
generatorName: python-experimental
|
||||
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
|
||||
generatorName: python
|
||||
outputDir: samples/openapi3/client/features/dynamic-servers/python/
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
6
bin/configs/python-legacy-oas2.yaml
Normal file
6
bin/configs/python-legacy-oas2.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
generatorName: python-legacy
|
||||
outputDir: samples/client/petstore/python-legacy
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python-legacy
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
6
bin/configs/python-legacy.yaml
Normal file
6
bin/configs/python-legacy.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
generatorName: python-legacy
|
||||
outputDir: samples/openapi3/client/petstore/python-legacy
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python-legacy
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
@ -1,6 +1,7 @@
|
||||
generatorName: python
|
||||
outputDir: samples/client/petstore/python
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/python-client-experimental/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
||||
disallowAdditionalPropertiesIfNotPresent: "true"
|
||||
packageName: petstore_api
|
||||
|
@ -1,7 +1,7 @@
|
||||
generatorName: python
|
||||
generatorName: python-legacy
|
||||
outputDir: samples/client/petstore/python-tornado
|
||||
library: tornado
|
||||
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
templateDir: modules/openapi-generator/src/main/resources/python-legacy
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
||||
|
@ -1,6 +1,7 @@
|
||||
generatorName: python
|
||||
outputDir: samples/openapi3/client/petstore/python
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml
|
||||
inputSpec: modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml
|
||||
templateDir: modules/openapi-generator/src/main/resources/python
|
||||
additionalProperties:
|
||||
packageName: petstore_api
|
||||
recursionLimit: "1234"
|
||||
|
@ -48,8 +48,8 @@ The following generators are available:
|
||||
* [perl](generators/perl.md)
|
||||
* [php](generators/php.md)
|
||||
* [powershell (beta)](generators/powershell.md)
|
||||
* [python](generators/python.md)
|
||||
* [python-experimental (experimental)](generators/python-experimental.md)
|
||||
* [python (experimental)](generators/python.md)
|
||||
* [python-legacy](generators/python-legacy.md)
|
||||
* [r](generators/r.md)
|
||||
* [ruby](generators/ruby.md)
|
||||
* [rust](generators/rust.md)
|
||||
|
@ -40,8 +40,8 @@ The following generators are available:
|
||||
* [perl](perl.md)
|
||||
* [php](php.md)
|
||||
* [powershell](powershell.md)
|
||||
* [python](python.md)
|
||||
* [python-experimental (experimental)](python-experimental.md)
|
||||
* [python](python.md)
|
||||
* [python-legacy](python-legacy.md)
|
||||
* [r](r.md)
|
||||
* [ruby](ruby.md)
|
||||
* [rust](rust.md)
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Config Options for python-experimental
|
||||
sidebar_label: python-experimental
|
||||
title: Config Options for python-legacy
|
||||
sidebar_label: python-legacy
|
||||
---
|
||||
|
||||
These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
|
||||
@ -14,8 +14,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|packageUrl|python package URL.| |null|
|
||||
|packageVersion|python package version.| |1.0.0|
|
||||
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|
||||
|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false|
|
||||
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|
||||
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|
||||
|useNose|use the nose test framework| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
@ -28,7 +28,6 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|
||||
| Type/Alias | Instantiated By |
|
||||
| ---------- | --------------- |
|
||||
|map|dict|
|
||||
|
||||
|
||||
## LANGUAGE PRIMITIVES
|
||||
@ -40,11 +39,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
<li>datetime</li>
|
||||
<li>dict</li>
|
||||
<li>file</li>
|
||||
<li>file_type</li>
|
||||
<li>float</li>
|
||||
<li>int</li>
|
||||
<li>list</li>
|
||||
<li>none_type</li>
|
||||
<li>object</li>
|
||||
<li>str</li>
|
||||
</ul>
|
||||
@ -167,7 +164,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|Examples|✓|OAS2,OAS3
|
||||
|XMLStructureDefinitions|✗|OAS2,OAS3
|
||||
|MultiServer|✗|OAS3
|
||||
|ParameterizedServer|✓|OAS3
|
||||
|ParameterizedServer|✗|OAS3
|
||||
|ParameterStyling|✗|OAS3
|
||||
|Callbacks|✗|OAS3
|
||||
|LinkObjects|✗|OAS3
|
@ -14,8 +14,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|packageUrl|python package URL.| |null|
|
||||
|packageVersion|python package version.| |1.0.0|
|
||||
|projectName|python project name in setup.py (e.g. petstore-api).| |null|
|
||||
|pythonAttrNoneIfUnset|when accessing unset attribute, return `None` instead of raising `ApiAttributeError`| |false|
|
||||
|recursionLimit|Set the recursion limit. If not set, use the system default value.| |null|
|
||||
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|
||||
|useNose|use the nose test framework| |false|
|
||||
|
||||
## IMPORT MAPPING
|
||||
@ -28,6 +28,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|
||||
| Type/Alias | Instantiated By |
|
||||
| ---------- | --------------- |
|
||||
|map|dict|
|
||||
|
||||
|
||||
## LANGUAGE PRIMITIVES
|
||||
@ -39,9 +40,11 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
<li>datetime</li>
|
||||
<li>dict</li>
|
||||
<li>file</li>
|
||||
<li>file_type</li>
|
||||
<li>float</li>
|
||||
<li>int</li>
|
||||
<li>list</li>
|
||||
<li>none_type</li>
|
||||
<li>object</li>
|
||||
<li>str</li>
|
||||
</ul>
|
||||
@ -164,7 +167,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|
||||
|Examples|✓|OAS2,OAS3
|
||||
|XMLStructureDefinitions|✗|OAS2,OAS3
|
||||
|MultiServer|✗|OAS3
|
||||
|ParameterizedServer|✗|OAS3
|
||||
|ParameterizedServer|✓|OAS3
|
||||
|ParameterStyling|✗|OAS3
|
||||
|Callbacks|✗|OAS3
|
||||
|LinkObjects|✗|OAS3
|
||||
|
@ -41,7 +41,7 @@ import org.openapitools.codegen.config.GlobalSettings;
|
||||
import org.openapitools.codegen.api.TemplatingEngineAdapter;
|
||||
import org.openapitools.codegen.api.TemplateFileType;
|
||||
import org.openapitools.codegen.ignore.CodegenIgnoreProcessor;
|
||||
import org.openapitools.codegen.languages.PythonClientExperimentalCodegen;
|
||||
import org.openapitools.codegen.languages.PythonClientCodegen;
|
||||
import org.openapitools.codegen.meta.GeneratorMetadata;
|
||||
import org.openapitools.codegen.meta.Stability;
|
||||
import org.openapitools.codegen.serializer.SerializerUtils;
|
||||
@ -520,9 +520,9 @@ public class DefaultGenerator implements Generator {
|
||||
Map<String, Object> modelTemplate = (Map<String, Object>) ((List<Object>) models.get("models")).get(0);
|
||||
if (modelTemplate != null && modelTemplate.containsKey("model")) {
|
||||
CodegenModel m = (CodegenModel) modelTemplate.get("model");
|
||||
if (m.isAlias && !(config instanceof PythonClientExperimentalCodegen)) {
|
||||
if (m.isAlias && !(config instanceof PythonClientCodegen)) {
|
||||
// alias to number, string, enum, etc, which should not be generated as model
|
||||
// for PythonClientExperimentalCodegen, all aliases are generated as models
|
||||
// for PythonClientCodegen, all aliases are generated as models
|
||||
continue; // Don't create user-defined classes for aliases
|
||||
}
|
||||
}
|
||||
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -89,8 +89,8 @@ org.openapitools.codegen.languages.PhpSymfonyServerCodegen
|
||||
org.openapitools.codegen.languages.PhpZendExpressivePathHandlerServerCodegen
|
||||
org.openapitools.codegen.languages.PowerShellClientCodegen
|
||||
org.openapitools.codegen.languages.ProtobufSchemaCodegen
|
||||
org.openapitools.codegen.languages.PythonLegacyClientCodegen
|
||||
org.openapitools.codegen.languages.PythonClientCodegen
|
||||
org.openapitools.codegen.languages.PythonClientExperimentalCodegen
|
||||
org.openapitools.codegen.languages.PythonFlaskConnexionServerCodegen
|
||||
org.openapitools.codegen.languages.PythonAiohttpConnexionServerCodegen
|
||||
org.openapitools.codegen.languages.PythonBluePlanetServerCodegen
|
||||
|
@ -17,7 +17,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
||||
|
||||
## Requirements.
|
||||
|
||||
Python >= 3.5
|
||||
Python 2.7 and 3.4+
|
||||
|
||||
## Installation & Usage
|
||||
### pip install
|
||||
@ -52,4 +52,4 @@ import {{{packageName}}}
|
||||
|
||||
Please follow the [installation procedure](#installation--usage) and then run the following:
|
||||
|
||||
{{> python-experimental/README_common }}
|
||||
{{> common_README }}
|
@ -17,7 +17,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
||||
|
||||
## Requirements.
|
||||
|
||||
Python >= 3.5
|
||||
Python 2.7 and 3.4+
|
||||
|
||||
## Installation & Usage
|
||||
|
||||
@ -26,6 +26,7 @@ This python library package is generated without supporting files like setup.py
|
||||
To be able to use it, you will need these dependencies in your own package that uses this library:
|
||||
|
||||
* urllib3 >= 1.15
|
||||
* six >= 1.10
|
||||
* certifi
|
||||
* python-dateutil
|
||||
{{#asyncio}}
|
||||
@ -40,4 +41,4 @@ To be able to use it, you will need these dependencies in your own package that
|
||||
In your own code, to use this library to connect and interact with {{{projectName}}},
|
||||
you can run the following:
|
||||
|
||||
{{> python-experimental/README_common }}
|
||||
{{> common_README }}
|
7
modules/openapi-generator/src/main/resources/python-legacy/__init__api.mustache
vendored
Normal file
7
modules/openapi-generator/src/main/resources/python-legacy/__init__api.mustache
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
# import apis into api package
|
||||
{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}}
|
||||
{{/apis}}{{/apiInfo}}
|
10
modules/openapi-generator/src/main/resources/python-legacy/__init__model.mustache
vendored
Normal file
10
modules/openapi-generator/src/main/resources/python-legacy/__init__model.mustache
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
# import models into model package
|
||||
{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}{{/model}}
|
||||
{{/models}}
|
@ -4,24 +4,25 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__version__ = "{{packageVersion}}"
|
||||
|
||||
# import apis into sdk package
|
||||
{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}}
|
||||
{{/apis}}{{/apiInfo}}
|
||||
# import ApiClient
|
||||
from {{packageName}}.api_client import ApiClient
|
||||
|
||||
# import Configuration
|
||||
from {{packageName}}.configuration import Configuration
|
||||
{{#hasHttpSignatureMethods}}
|
||||
from {{packageName}}.signing import HttpSigningConfiguration
|
||||
{{/hasHttpSignatureMethods}}
|
||||
|
||||
# import exceptions
|
||||
from {{packageName}}.exceptions import OpenApiException
|
||||
from {{packageName}}.exceptions import ApiAttributeError
|
||||
from {{packageName}}.exceptions import ApiTypeError
|
||||
from {{packageName}}.exceptions import ApiValueError
|
||||
from {{packageName}}.exceptions import ApiKeyError
|
||||
from {{packageName}}.exceptions import ApiAttributeError
|
||||
from {{packageName}}.exceptions import ApiException
|
||||
# import models into sdk package
|
||||
{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}
|
||||
{{/model}}{{/models}}
|
||||
{{#recursionLimit}}
|
||||
|
||||
__import__('sys').setrecursionlimit({{{.}}})
|
294
modules/openapi-generator/src/main/resources/python-legacy/api.mustache
vendored
Normal file
294
modules/openapi-generator/src/main/resources/python-legacy/api.mustache
vendored
Normal file
@ -0,0 +1,294 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import re # noqa: F401
|
||||
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
|
||||
from {{packageName}}.api_client import ApiClient
|
||||
from {{packageName}}.exceptions import ( # noqa: F401
|
||||
ApiTypeError,
|
||||
ApiValueError
|
||||
)
|
||||
|
||||
|
||||
{{#operations}}
|
||||
class {{classname}}(object):
|
||||
"""NOTE: This class is auto generated by OpenAPI Generator
|
||||
Ref: https://openapi-generator.tech
|
||||
|
||||
Do not edit the class manually.
|
||||
"""
|
||||
|
||||
def __init__(self, api_client=None):
|
||||
if api_client is None:
|
||||
api_client = ApiClient()
|
||||
self.api_client = api_client
|
||||
{{#operation}}
|
||||
|
||||
def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
|
||||
{{#notes}}
|
||||
{{{notes}}} # noqa: E501
|
||||
{{/notes}}
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
|
||||
{{#sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
{{^sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
>>> result = thread.get()
|
||||
|
||||
{{#allParams}}
|
||||
:param {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
|
||||
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
|
||||
{{/allParams}}
|
||||
:param async_req: Whether to execute the request asynchronously.
|
||||
:type async_req: bool, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:return: Returns the result object.
|
||||
If the method is called asynchronously,
|
||||
returns the request thread.
|
||||
:rtype: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
"""
|
||||
kwargs['_return_http_data_only'] = True
|
||||
return self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) # noqa: E501
|
||||
|
||||
def {{operationId}}_with_http_info(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
|
||||
{{#notes}}
|
||||
{{{notes}}} # noqa: E501
|
||||
{{/notes}}
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
|
||||
{{#sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
{{^sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
>>> result = thread.get()
|
||||
|
||||
{{#allParams}}
|
||||
:param {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
|
||||
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
|
||||
{{/allParams}}
|
||||
:param async_req: Whether to execute the request asynchronously.
|
||||
:type async_req: bool, optional
|
||||
:param _return_http_data_only: response data without head status code
|
||||
and headers
|
||||
:type _return_http_data_only: bool, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the authentication
|
||||
in the spec for a single request.
|
||||
:type _request_auth: dict, optional
|
||||
:return: Returns the result object.
|
||||
If the method is called asynchronously,
|
||||
returns the request thread.
|
||||
:rtype: {{#returnType}}tuple({{returnType}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
"""
|
||||
|
||||
{{#servers.0}}
|
||||
local_var_hosts = [
|
||||
{{#servers}}
|
||||
'{{{url}}}'{{^-last}},{{/-last}}
|
||||
{{/servers}}
|
||||
]
|
||||
local_var_host = local_var_hosts[0]
|
||||
if kwargs.get('_host_index'):
|
||||
_host_index = int(kwargs.get('_host_index'))
|
||||
if _host_index < 0 or _host_index >= len(local_var_hosts):
|
||||
raise ApiValueError(
|
||||
"Invalid host index. Must be 0 <= index < %s"
|
||||
% len(local_var_host)
|
||||
)
|
||||
local_var_host = local_var_hosts[_host_index]
|
||||
{{/servers.0}}
|
||||
local_var_params = locals()
|
||||
|
||||
all_params = [
|
||||
{{#allParams}}
|
||||
'{{paramName}}'{{^-last}},{{/-last}}
|
||||
{{/allParams}}
|
||||
]
|
||||
all_params.extend(
|
||||
[
|
||||
'async_req',
|
||||
'_return_http_data_only',
|
||||
'_preload_content',
|
||||
'_request_timeout',
|
||||
'_request_auth'
|
||||
]
|
||||
)
|
||||
|
||||
for key, val in six.iteritems(local_var_params['kwargs']):
|
||||
if key not in all_params{{#servers.0}} and key != "_host_index"{{/servers.0}}:
|
||||
raise ApiTypeError(
|
||||
"Got an unexpected keyword argument '%s'"
|
||||
" to method {{operationId}}" % key
|
||||
)
|
||||
local_var_params[key] = val
|
||||
del local_var_params['kwargs']
|
||||
{{#allParams}}
|
||||
{{^isNullable}}
|
||||
{{#required}}
|
||||
# verify the required parameter '{{paramName}}' is set
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' not in local_var_params or # noqa: E501
|
||||
local_var_params['{{paramName}}'] is None): # noqa: E501
|
||||
raise ApiValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") # noqa: E501
|
||||
{{/required}}
|
||||
{{/isNullable}}
|
||||
{{/allParams}}
|
||||
|
||||
{{#allParams}}
|
||||
{{#hasValidation}}
|
||||
{{#maxLength}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) > {{maxLength}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501
|
||||
{{/maxLength}}
|
||||
{{#minLength}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) < {{minLength}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501
|
||||
{{/minLength}}
|
||||
{{#maximum}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501
|
||||
{{/maximum}}
|
||||
{{#minimum}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501
|
||||
{{/minimum}}
|
||||
{{#pattern}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and not re.search(r'{{{vendorExtensions.x-regex}}}', local_var_params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") # noqa: E501
|
||||
{{/pattern}}
|
||||
{{#maxItems}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) > {{maxItems}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501
|
||||
{{/maxItems}}
|
||||
{{#minItems}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) < {{minItems}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501
|
||||
{{/minItems}}
|
||||
{{/hasValidation}}
|
||||
{{#-last}}
|
||||
{{/-last}}
|
||||
{{/allParams}}
|
||||
collection_formats = {}
|
||||
|
||||
path_params = {}
|
||||
{{#pathParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
path_params['{{baseName}}'] = local_var_params['{{paramName}}']{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/pathParams}}
|
||||
|
||||
query_params = []
|
||||
{{#queryParams}}
|
||||
if '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] is not None: # noqa: E501
|
||||
query_params.append(('{{baseName}}', local_var_params['{{paramName}}'])){{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/queryParams}}
|
||||
|
||||
header_params = {}
|
||||
{{#headerParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
header_params['{{baseName}}'] = local_var_params['{{paramName}}']{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/headerParams}}
|
||||
|
||||
form_params = []
|
||||
local_var_files = {}
|
||||
{{#formParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
{{^isFile}}form_params.append(('{{baseName}}', local_var_params['{{paramName}}'])){{/isFile}}{{#isFile}}local_var_files['{{baseName}}'] = local_var_params['{{paramName}}']{{/isFile}}{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/formParams}}
|
||||
|
||||
body_params = None
|
||||
{{#bodyParam}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
body_params = local_var_params['{{paramName}}']
|
||||
{{/bodyParam}}
|
||||
{{#hasProduces}}
|
||||
# HTTP header `Accept`
|
||||
header_params['Accept'] = self.api_client.select_header_accept(
|
||||
[{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501
|
||||
|
||||
{{/hasProduces}}
|
||||
{{#hasConsumes}}
|
||||
# HTTP header `Content-Type`
|
||||
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
|
||||
[{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]) # noqa: E501
|
||||
|
||||
{{/hasConsumes}}
|
||||
# Authentication setting
|
||||
auth_settings = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501
|
||||
|
||||
{{#returnType}}
|
||||
{{#responses}}
|
||||
{{#-first}}
|
||||
response_types_map = {
|
||||
{{/-first}}
|
||||
{{^isWildcard}}
|
||||
{{code}}: {{#dataType}}"{{dataType}}"{{/dataType}}{{^dataType}}None{{/dataType}},
|
||||
{{/isWildcard}}
|
||||
{{#-last}}
|
||||
}
|
||||
{{/-last}}
|
||||
{{/responses}}
|
||||
{{/returnType}}
|
||||
{{^returnType}}
|
||||
response_types_map = {}
|
||||
{{/returnType}}
|
||||
|
||||
return self.api_client.call_api(
|
||||
'{{{path}}}', '{{httpMethod}}',
|
||||
path_params,
|
||||
query_params,
|
||||
header_params,
|
||||
body=body_params,
|
||||
post_params=form_params,
|
||||
files=local_var_files,
|
||||
response_types_map=response_types_map,
|
||||
auth_settings=auth_settings,
|
||||
async_req=local_var_params.get('async_req'),
|
||||
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
|
||||
_preload_content=local_var_params.get('_preload_content', True),
|
||||
_request_timeout=local_var_params.get('_request_timeout'),
|
||||
{{#servers.0}}
|
||||
_host=local_var_host,
|
||||
{{/servers.0}}
|
||||
collection_formats=collection_formats,
|
||||
_request_auth=local_var_params.get('_request_auth'))
|
||||
{{/operation}}
|
||||
{{/operations}}
|
717
modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache
vendored
Normal file
717
modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache
vendored
Normal file
@ -0,0 +1,717 @@
|
||||
# coding: utf-8
|
||||
{{>partial_header}}
|
||||
from __future__ import absolute_import
|
||||
|
||||
import atexit
|
||||
import datetime
|
||||
from dateutil.parser import parse
|
||||
import json
|
||||
import mimetypes
|
||||
from multiprocessing.pool import ThreadPool
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
from six.moves.urllib.parse import quote
|
||||
{{#tornado}}
|
||||
import tornado.gen
|
||||
{{/tornado}}
|
||||
|
||||
from {{packageName}}.configuration import Configuration
|
||||
import {{modelPackage}}
|
||||
from {{packageName}} import rest
|
||||
from {{packageName}}.exceptions import ApiValueError, ApiException
|
||||
|
||||
|
||||
class ApiClient(object):
|
||||
"""Generic API client for OpenAPI client library builds.
|
||||
|
||||
OpenAPI generic API client. This client handles the client-
|
||||
server communication, and is invariant across implementations. Specifics of
|
||||
the methods and models for each application are generated from the OpenAPI
|
||||
templates.
|
||||
|
||||
NOTE: This class is auto generated by OpenAPI Generator.
|
||||
Ref: https://openapi-generator.tech
|
||||
Do not edit the class manually.
|
||||
|
||||
:param configuration: .Configuration object for this client
|
||||
:param header_name: a header to pass when making calls to the API.
|
||||
:param header_value: a header value to pass when making calls to
|
||||
the API.
|
||||
:param cookie: a cookie to include in the header when making calls
|
||||
to the API
|
||||
:param pool_threads: The number of threads to use for async requests
|
||||
to the API. More threads means more concurrent API requests.
|
||||
"""
|
||||
|
||||
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
|
||||
NATIVE_TYPES_MAPPING = {
|
||||
'int': int,
|
||||
'long': int if six.PY3 else long, # noqa: F821
|
||||
'float': float,
|
||||
'str': str,
|
||||
'bool': bool,
|
||||
'date': datetime.date,
|
||||
'datetime': datetime.datetime,
|
||||
'object': object,
|
||||
}
|
||||
_pool = None
|
||||
|
||||
def __init__(self, configuration=None, header_name=None, header_value=None,
|
||||
cookie=None, pool_threads=1):
|
||||
if configuration is None:
|
||||
configuration = Configuration.get_default_copy()
|
||||
self.configuration = configuration
|
||||
self.pool_threads = pool_threads
|
||||
|
||||
self.rest_client = rest.RESTClientObject(configuration)
|
||||
self.default_headers = {}
|
||||
if header_name is not None:
|
||||
self.default_headers[header_name] = header_value
|
||||
self.cookie = cookie
|
||||
# Set default User-Agent.
|
||||
self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}'
|
||||
self.client_side_validation = configuration.client_side_validation
|
||||
|
||||
{{#asyncio}}
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_value, traceback):
|
||||
await self.close()
|
||||
{{/asyncio}}
|
||||
{{^asyncio}}
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.close()
|
||||
{{/asyncio}}
|
||||
|
||||
{{#asyncio}}async {{/asyncio}}def close(self):
|
||||
{{#asyncio}}
|
||||
await self.rest_client.close()
|
||||
{{/asyncio}}
|
||||
if self._pool:
|
||||
self._pool.close()
|
||||
self._pool.join()
|
||||
self._pool = None
|
||||
if hasattr(atexit, 'unregister'):
|
||||
atexit.unregister(self.close)
|
||||
|
||||
@property
|
||||
def pool(self):
|
||||
"""Create thread pool on first request
|
||||
avoids instantiating unused threadpool for blocking clients.
|
||||
"""
|
||||
if self._pool is None:
|
||||
atexit.register(self.close)
|
||||
self._pool = ThreadPool(self.pool_threads)
|
||||
return self._pool
|
||||
|
||||
@property
|
||||
def user_agent(self):
|
||||
"""User agent for this API client"""
|
||||
return self.default_headers['User-Agent']
|
||||
|
||||
@user_agent.setter
|
||||
def user_agent(self, value):
|
||||
self.default_headers['User-Agent'] = value
|
||||
|
||||
def set_default_header(self, header_name, header_value):
|
||||
self.default_headers[header_name] = header_value
|
||||
|
||||
{{#tornado}}
|
||||
@tornado.gen.coroutine
|
||||
{{/tornado}}
|
||||
{{#asyncio}}async {{/asyncio}}def __call_api(
|
||||
self, resource_path, method, path_params=None,
|
||||
query_params=None, header_params=None, body=None, post_params=None,
|
||||
files=None, response_types_map=None, auth_settings=None,
|
||||
_return_http_data_only=None, collection_formats=None,
|
||||
_preload_content=True, _request_timeout=None, _host=None,
|
||||
_request_auth=None):
|
||||
|
||||
config = self.configuration
|
||||
|
||||
# header parameters
|
||||
header_params = header_params or {}
|
||||
header_params.update(self.default_headers)
|
||||
if self.cookie:
|
||||
header_params['Cookie'] = self.cookie
|
||||
if header_params:
|
||||
header_params = self.sanitize_for_serialization(header_params)
|
||||
header_params = dict(self.parameters_to_tuples(header_params,
|
||||
collection_formats))
|
||||
|
||||
# path parameters
|
||||
if path_params:
|
||||
path_params = self.sanitize_for_serialization(path_params)
|
||||
path_params = self.parameters_to_tuples(path_params,
|
||||
collection_formats)
|
||||
for k, v in path_params:
|
||||
# specified safe chars, encode everything
|
||||
resource_path = resource_path.replace(
|
||||
'{%s}' % k,
|
||||
quote(str(v), safe=config.safe_chars_for_path_param)
|
||||
)
|
||||
|
||||
# query parameters
|
||||
if query_params:
|
||||
query_params = self.sanitize_for_serialization(query_params)
|
||||
query_params = self.parameters_to_tuples(query_params,
|
||||
collection_formats)
|
||||
|
||||
# post parameters
|
||||
if post_params or files:
|
||||
post_params = post_params if post_params else []
|
||||
post_params = self.sanitize_for_serialization(post_params)
|
||||
post_params = self.parameters_to_tuples(post_params,
|
||||
collection_formats)
|
||||
post_params.extend(self.files_parameters(files))
|
||||
|
||||
# auth setting
|
||||
self.update_params_for_auth(
|
||||
header_params, query_params, auth_settings,
|
||||
request_auth=_request_auth)
|
||||
|
||||
# body
|
||||
if body:
|
||||
body = self.sanitize_for_serialization(body)
|
||||
|
||||
# request url
|
||||
if _host is None:
|
||||
url = self.configuration.host + resource_path
|
||||
else:
|
||||
# use server/host defined in path or operation instead
|
||||
url = _host + resource_path
|
||||
|
||||
try:
|
||||
# perform request and return response
|
||||
response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request(
|
||||
method, url, query_params=query_params, headers=header_params,
|
||||
post_params=post_params, body=body,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout)
|
||||
except ApiException as e:
|
||||
e.body = e.body.decode('utf-8') if six.PY3 else e.body
|
||||
raise e
|
||||
|
||||
self.last_response = response_data
|
||||
|
||||
return_data = response_data
|
||||
|
||||
if not _preload_content:
|
||||
{{^tornado}}
|
||||
return return_data
|
||||
{{/tornado}}
|
||||
{{#tornado}}
|
||||
raise tornado.gen.Return(return_data)
|
||||
{{/tornado}}
|
||||
|
||||
response_type = response_types_map.get(response_data.status, None)
|
||||
|
||||
if six.PY3 and response_type not in ["file", "bytes"]:
|
||||
match = None
|
||||
content_type = response_data.getheader('content-type')
|
||||
if content_type is not None:
|
||||
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
|
||||
encoding = match.group(1) if match else "utf-8"
|
||||
response_data.data = response_data.data.decode(encoding)
|
||||
|
||||
# deserialize response data
|
||||
|
||||
if response_type:
|
||||
return_data = self.deserialize(response_data, response_type)
|
||||
else:
|
||||
return_data = None
|
||||
|
||||
{{^tornado}}
|
||||
if _return_http_data_only:
|
||||
return (return_data)
|
||||
else:
|
||||
return (return_data, response_data.status,
|
||||
response_data.getheaders())
|
||||
{{/tornado}}
|
||||
{{#tornado}}
|
||||
if _return_http_data_only:
|
||||
raise tornado.gen.Return(return_data)
|
||||
else:
|
||||
raise tornado.gen.Return((return_data, response_data.status,
|
||||
response_data.getheaders()))
|
||||
{{/tornado}}
|
||||
|
||||
def sanitize_for_serialization(self, obj):
|
||||
"""Builds a JSON POST object.
|
||||
|
||||
If obj is None, return None.
|
||||
If obj is str, int, long, float, bool, return directly.
|
||||
If obj is datetime.datetime, datetime.date
|
||||
convert to string in iso8601 format.
|
||||
If obj is list, sanitize each element in the list.
|
||||
If obj is dict, return the dict.
|
||||
If obj is OpenAPI model, return the properties dict.
|
||||
|
||||
:param obj: The data to serialize.
|
||||
:return: The serialized form of data.
|
||||
"""
|
||||
if obj is None:
|
||||
return None
|
||||
elif isinstance(obj, self.PRIMITIVE_TYPES):
|
||||
return obj
|
||||
elif isinstance(obj, list):
|
||||
return [self.sanitize_for_serialization(sub_obj)
|
||||
for sub_obj in obj]
|
||||
elif isinstance(obj, tuple):
|
||||
return tuple(self.sanitize_for_serialization(sub_obj)
|
||||
for sub_obj in obj)
|
||||
elif isinstance(obj, (datetime.datetime, datetime.date)):
|
||||
return obj.isoformat()
|
||||
|
||||
if isinstance(obj, dict):
|
||||
obj_dict = obj
|
||||
else:
|
||||
# Convert model obj to dict except
|
||||
# attributes `openapi_types`, `attribute_map`
|
||||
# and attributes which value is not None.
|
||||
# Convert attribute name to json key in
|
||||
# model definition for request.
|
||||
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
|
||||
for attr, _ in six.iteritems(obj.openapi_types)
|
||||
if getattr(obj, attr) is not None}
|
||||
|
||||
return {key: self.sanitize_for_serialization(val)
|
||||
for key, val in six.iteritems(obj_dict)}
|
||||
|
||||
def deserialize(self, response, response_type):
|
||||
"""Deserializes response into an object.
|
||||
|
||||
:param response: RESTResponse object to be deserialized.
|
||||
:param response_type: class literal for
|
||||
deserialized object, or string of class name.
|
||||
|
||||
:return: deserialized object.
|
||||
"""
|
||||
# handle file downloading
|
||||
# save response body into a tmp file and return the instance
|
||||
if response_type == "file":
|
||||
return self.__deserialize_file(response)
|
||||
|
||||
# fetch data from response object
|
||||
try:
|
||||
data = json.loads(response.data)
|
||||
except ValueError:
|
||||
data = response.data
|
||||
|
||||
return self.__deserialize(data, response_type)
|
||||
|
||||
def __deserialize(self, data, klass):
|
||||
"""Deserializes dict, list, str into an object.
|
||||
|
||||
:param data: dict, list or str.
|
||||
:param klass: class literal, or string of class name.
|
||||
|
||||
:return: object.
|
||||
"""
|
||||
if data is None:
|
||||
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_datetime(data)
|
||||
else:
|
||||
return self.__deserialize_model(data, klass)
|
||||
|
||||
def call_api(self, resource_path, method,
|
||||
path_params=None, query_params=None, header_params=None,
|
||||
body=None, post_params=None, files=None,
|
||||
response_types_map=None, auth_settings=None,
|
||||
async_req=None, _return_http_data_only=None,
|
||||
collection_formats=None,_preload_content=True,
|
||||
_request_timeout=None, _host=None, _request_auth=None):
|
||||
"""Makes the HTTP request (synchronous) and returns deserialized data.
|
||||
|
||||
To make an async_req request, set the async_req parameter.
|
||||
|
||||
:param resource_path: Path to method endpoint.
|
||||
:param method: Method to call.
|
||||
:param path_params: Path parameters in the url.
|
||||
:param query_params: Query parameters in the url.
|
||||
:param header_params: Header parameters to be
|
||||
placed in the request header.
|
||||
:param body: Request body.
|
||||
:param post_params dict: Request post form parameters,
|
||||
for `application/x-www-form-urlencoded`, `multipart/form-data`.
|
||||
:param auth_settings list: Auth Settings names for the request.
|
||||
:param response: Response data type.
|
||||
:param files dict: key -> filename, value -> filepath,
|
||||
for `multipart/form-data`.
|
||||
:param async_req bool: execute request asynchronously
|
||||
:param _return_http_data_only: response data without head status code
|
||||
and headers
|
||||
:param collection_formats: dict of collection formats for path, query,
|
||||
header, and post parameters.
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the authentication
|
||||
in the spec for a single request.
|
||||
:type _request_token: dict, optional
|
||||
:return:
|
||||
If async_req parameter is True,
|
||||
the request will be called asynchronously.
|
||||
The method will return the request thread.
|
||||
If parameter async_req is False or missing,
|
||||
then the method will return the response directly.
|
||||
"""
|
||||
if not async_req:
|
||||
return self.__call_api(resource_path, method,
|
||||
path_params, query_params, header_params,
|
||||
body, post_params, files,
|
||||
response_types_map, auth_settings,
|
||||
_return_http_data_only, collection_formats,
|
||||
_preload_content, _request_timeout, _host,
|
||||
_request_auth)
|
||||
|
||||
return self.pool.apply_async(self.__call_api, (resource_path,
|
||||
method, path_params,
|
||||
query_params,
|
||||
header_params, body,
|
||||
post_params, files,
|
||||
response_types_map,
|
||||
auth_settings,
|
||||
_return_http_data_only,
|
||||
collection_formats,
|
||||
_preload_content,
|
||||
_request_timeout,
|
||||
_host, _request_auth))
|
||||
|
||||
def request(self, method, url, query_params=None, headers=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
"""Makes the HTTP request using RESTClient."""
|
||||
if method == "GET":
|
||||
return self.rest_client.GET(url,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
headers=headers)
|
||||
elif method == "HEAD":
|
||||
return self.rest_client.HEAD(url,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
headers=headers)
|
||||
elif method == "OPTIONS":
|
||||
return self.rest_client.OPTIONS(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout)
|
||||
elif method == "POST":
|
||||
return self.rest_client.POST(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "PUT":
|
||||
return self.rest_client.PUT(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "PATCH":
|
||||
return self.rest_client.PATCH(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "DELETE":
|
||||
return self.rest_client.DELETE(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
else:
|
||||
raise ApiValueError(
|
||||
"http method must be `GET`, `HEAD`, `OPTIONS`,"
|
||||
" `POST`, `PATCH`, `PUT` or `DELETE`."
|
||||
)
|
||||
|
||||
def parameters_to_tuples(self, params, collection_formats):
|
||||
"""Get parameters as list of tuples, formatting collections.
|
||||
|
||||
:param params: Parameters as dict or list of two-tuples
|
||||
:param dict collection_formats: Parameter collection formats
|
||||
:return: Parameters as list of tuples, collections formatted
|
||||
"""
|
||||
new_params = []
|
||||
if collection_formats is None:
|
||||
collection_formats = {}
|
||||
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
|
||||
if k in collection_formats:
|
||||
collection_format = collection_formats[k]
|
||||
if collection_format == 'multi':
|
||||
new_params.extend((k, value) for value in v)
|
||||
else:
|
||||
if collection_format == 'ssv':
|
||||
delimiter = ' '
|
||||
elif collection_format == 'tsv':
|
||||
delimiter = '\t'
|
||||
elif collection_format == 'pipes':
|
||||
delimiter = '|'
|
||||
else: # csv is the default
|
||||
delimiter = ','
|
||||
new_params.append(
|
||||
(k, delimiter.join(str(value) for value in v)))
|
||||
else:
|
||||
new_params.append((k, v))
|
||||
return new_params
|
||||
|
||||
def files_parameters(self, files=None):
|
||||
"""Builds form parameters.
|
||||
|
||||
:param files: File parameters.
|
||||
:return: Form parameters with files.
|
||||
"""
|
||||
params = []
|
||||
|
||||
if files:
|
||||
for k, v in six.iteritems(files):
|
||||
if not v:
|
||||
continue
|
||||
file_names = v if type(v) is list else [v]
|
||||
for n in file_names:
|
||||
with open(n, 'rb') as f:
|
||||
filename = os.path.basename(f.name)
|
||||
filedata = f.read()
|
||||
mimetype = (mimetypes.guess_type(filename)[0] or
|
||||
'application/octet-stream')
|
||||
params.append(
|
||||
tuple([k, tuple([filename, filedata, mimetype])]))
|
||||
|
||||
return params
|
||||
|
||||
def select_header_accept(self, accepts):
|
||||
"""Returns `Accept` based on an array of accepts provided.
|
||||
|
||||
:param accepts: List of headers.
|
||||
:return: Accept (e.g. application/json).
|
||||
"""
|
||||
if not accepts:
|
||||
return
|
||||
|
||||
accepts = [x.lower() for x in accepts]
|
||||
|
||||
if 'application/json' in accepts:
|
||||
return 'application/json'
|
||||
else:
|
||||
return ', '.join(accepts)
|
||||
|
||||
def select_header_content_type(self, content_types):
|
||||
"""Returns `Content-Type` based on an array of content_types provided.
|
||||
|
||||
:param content_types: List of content-types.
|
||||
:return: Content-Type (e.g. application/json).
|
||||
"""
|
||||
if not content_types:
|
||||
return 'application/json'
|
||||
|
||||
content_types = [x.lower() for x in content_types]
|
||||
|
||||
if 'application/json' in content_types or '*/*' in content_types:
|
||||
return 'application/json'
|
||||
else:
|
||||
return content_types[0]
|
||||
|
||||
def update_params_for_auth(self, headers, querys, auth_settings,
|
||||
request_auth=None):
|
||||
"""Updates header and query params based on authentication setting.
|
||||
|
||||
:param headers: Header parameters dict to be updated.
|
||||
:param querys: Query parameters tuple list to be updated.
|
||||
:param auth_settings: Authentication setting identifiers list.
|
||||
:param request_auth: if set, the provided settings will
|
||||
override the token in the configuration.
|
||||
"""
|
||||
if not auth_settings:
|
||||
return
|
||||
|
||||
if request_auth:
|
||||
self._apply_auth_params(headers, querys, request_auth)
|
||||
return
|
||||
|
||||
for auth in auth_settings:
|
||||
auth_setting = self.configuration.auth_settings().get(auth)
|
||||
if auth_setting:
|
||||
self._apply_auth_params(headers, querys, auth_setting)
|
||||
|
||||
def _apply_auth_params(self, headers, querys, auth_setting):
|
||||
"""Updates the request parameters based on a single auth_setting
|
||||
|
||||
:param headers: Header parameters dict to be updated.
|
||||
:param querys: Query parameters tuple list to be updated.
|
||||
:param auth_setting: auth settings for the endpoint
|
||||
"""
|
||||
if auth_setting['in'] == 'cookie':
|
||||
headers['Cookie'] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'header':
|
||||
headers[auth_setting['key']] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'query':
|
||||
querys.append((auth_setting['key'], auth_setting['value']))
|
||||
else:
|
||||
raise ApiValueError(
|
||||
'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
|
||||
|
||||
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:
|
||||
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_datetime(self, string):
|
||||
"""Deserializes string to datetime.
|
||||
|
||||
The string should be in iso8601 datetime format.
|
||||
|
||||
:param string: str.
|
||||
:return: datetime.
|
||||
"""
|
||||
try:
|
||||
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.
|
||||
:return: model object.
|
||||
"""
|
||||
has_discriminator = False
|
||||
if (hasattr(klass, 'get_real_child_model')
|
||||
and klass.discriminator_value_class_map):
|
||||
has_discriminator = True
|
||||
|
||||
if not klass.openapi_types and has_discriminator is False:
|
||||
return data
|
||||
|
||||
kwargs = {}
|
||||
if (data is not None and
|
||||
klass.openapi_types is not None and
|
||||
isinstance(data, (list, dict))):
|
||||
for attr, attr_type in six.iteritems(klass.openapi_types):
|
||||
if klass.attribute_map[attr] in data:
|
||||
value = data[klass.attribute_map[attr]]
|
||||
kwargs[attr] = self.__deserialize(value, attr_type)
|
||||
|
||||
instance = klass(**kwargs)
|
||||
|
||||
if has_discriminator:
|
||||
klass_name = instance.get_real_child_model(data)
|
||||
if klass_name:
|
||||
instance = self.__deserialize(data, klass_name)
|
||||
return instance
|
@ -11,7 +11,7 @@ Method | HTTP request | Description
|
||||
{{#operations}}
|
||||
{{#operation}}
|
||||
# **{{{operationId}}}**
|
||||
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}{{^-last}}, {{/-last}}{{/defaultValue}}{{/requiredParams}})
|
||||
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}={{{paramName}}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
|
||||
|
||||
{{{summary}}}{{#notes}}
|
||||
|
||||
@ -35,17 +35,18 @@ Method | HTTP request | Description
|
||||
{{#isOAuth}}
|
||||
* OAuth Authentication ({{name}}):
|
||||
{{/isOAuth }}
|
||||
{{> api_doc_example }}
|
||||
{{/authMethods}}
|
||||
{{/hasAuthMethods}}
|
||||
{{> python-experimental/api_doc_example }}
|
||||
{{^hasAuthMethods}}
|
||||
{{> api_doc_example }}
|
||||
{{/hasAuthMethods}}
|
||||
### Parameters
|
||||
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
|
||||
Name | Type | Description | Notes
|
||||
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
|
||||
{{#requiredParams}}{{^defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} |
|
||||
{{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | defaults to {{{.}}}
|
||||
{{/defaultValue}}{{/requiredParams}}{{#optionalParams}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | [optional]{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}}
|
||||
{{/optionalParams}}
|
||||
{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
|
||||
{{/allParams}}
|
||||
|
||||
### Return type
|
||||
|
26
modules/openapi-generator/src/main/resources/python-legacy/api_doc_example.mustache
vendored
Normal file
26
modules/openapi-generator/src/main/resources/python-legacy/api_doc_example.mustache
vendored
Normal file
@ -0,0 +1,26 @@
|
||||
```python
|
||||
from __future__ import print_function
|
||||
import time
|
||||
import {{{packageName}}}
|
||||
from {{{packageName}}}.rest import ApiException
|
||||
from pprint import pprint
|
||||
{{> python_doc_auth_partial}}
|
||||
# Enter a context with an instance of the API client
|
||||
{{#hasAuthMethods}}
|
||||
with {{{packageName}}}.ApiClient(configuration) as api_client:
|
||||
{{/hasAuthMethods}}
|
||||
{{^hasAuthMethods}}
|
||||
with {{{packageName}}}.ApiClient() as api_client:
|
||||
{{/hasAuthMethods}}
|
||||
# Create an instance of the API class
|
||||
api_instance = {{{packageName}}}.{{{classname}}}(api_client)
|
||||
{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
||||
{{/allParams}}
|
||||
|
||||
try:
|
||||
{{#summary}} # {{{.}}}
|
||||
{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}
|
||||
pprint(api_response){{/returnType}}
|
||||
except ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
```
|
@ -2,17 +2,20 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import unittest
|
||||
|
||||
import {{packageName}}
|
||||
from {{apiPackage}}.{{classVarName}} import {{classname}} # noqa: E501
|
||||
from {{packageName}}.rest import ApiException
|
||||
|
||||
|
||||
class {{#operations}}Test{{classname}}(unittest.TestCase):
|
||||
"""{{classname}} unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
self.api = {{classname}}() # noqa: E501
|
||||
self.api = {{apiPackage}}.{{classVarName}}.{{classname}}() # noqa: E501
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
246
modules/openapi-generator/src/main/resources/python-legacy/asyncio/rest.mustache
vendored
Normal file
246
modules/openapi-generator/src/main/resources/python-legacy/asyncio/rest.mustache
vendored
Normal file
@ -0,0 +1,246 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import ssl
|
||||
|
||||
import aiohttp
|
||||
import certifi
|
||||
# python 2 and python 3 compatibility library
|
||||
from six.moves.urllib.parse import urlencode
|
||||
|
||||
from {{packageName}}.exceptions import ApiException, ApiValueError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RESTResponse(io.IOBase):
|
||||
|
||||
def __init__(self, resp, data):
|
||||
self.aiohttp_response = resp
|
||||
self.status = resp.status
|
||||
self.reason = resp.reason
|
||||
self.data = data
|
||||
|
||||
def getheaders(self):
|
||||
"""Returns a CIMultiDictProxy of the response headers."""
|
||||
return self.aiohttp_response.headers
|
||||
|
||||
def getheader(self, name, default=None):
|
||||
"""Returns a given response header."""
|
||||
return self.aiohttp_response.headers.get(name, default)
|
||||
|
||||
|
||||
class RESTClientObject(object):
|
||||
|
||||
def __init__(self, configuration, pools_size=4, maxsize=None):
|
||||
|
||||
# maxsize is number of requests to host that are allowed in parallel
|
||||
if maxsize is None:
|
||||
maxsize = configuration.connection_pool_maxsize
|
||||
|
||||
# ca_certs
|
||||
if configuration.ssl_ca_cert:
|
||||
ca_certs = configuration.ssl_ca_cert
|
||||
else:
|
||||
# if not set certificate file, use Mozilla's root certificates.
|
||||
ca_certs = certifi.where()
|
||||
|
||||
ssl_context = ssl.create_default_context(cafile=ca_certs)
|
||||
if configuration.cert_file:
|
||||
ssl_context.load_cert_chain(
|
||||
configuration.cert_file, keyfile=configuration.key_file
|
||||
)
|
||||
|
||||
if not configuration.verify_ssl:
|
||||
ssl_context.check_hostname = False
|
||||
ssl_context.verify_mode = ssl.CERT_NONE
|
||||
|
||||
connector = aiohttp.TCPConnector(
|
||||
limit=maxsize,
|
||||
ssl=ssl_context
|
||||
)
|
||||
|
||||
self.proxy = configuration.proxy
|
||||
self.proxy_headers = configuration.proxy_headers
|
||||
|
||||
# https pool manager
|
||||
self.pool_manager = aiohttp.ClientSession(
|
||||
connector=connector
|
||||
)
|
||||
|
||||
async def close(self):
|
||||
await self.pool_manager.close()
|
||||
|
||||
async def request(self, method, url, query_params=None, headers=None,
|
||||
body=None, post_params=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
"""Execute request
|
||||
|
||||
:param method: http request method
|
||||
:param url: http request url
|
||||
:param query_params: query parameters in the url
|
||||
:param headers: http request headers
|
||||
:param body: request json body, for `application/json`
|
||||
:param post_params: request post parameters,
|
||||
`application/x-www-form-urlencoded`
|
||||
and `multipart/form-data`
|
||||
:param _preload_content: this is a non-applicable field for
|
||||
the AiohttpClient.
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
"""
|
||||
method = method.upper()
|
||||
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT',
|
||||
'PATCH', 'OPTIONS']
|
||||
|
||||
if post_params and body:
|
||||
raise ApiValueError(
|
||||
"body parameter cannot be used with post_params parameter."
|
||||
)
|
||||
|
||||
post_params = post_params or {}
|
||||
headers = headers or {}
|
||||
timeout = _request_timeout or 5 * 60
|
||||
|
||||
if 'Content-Type' not in headers:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
|
||||
args = {
|
||||
"method": method,
|
||||
"url": url,
|
||||
"timeout": timeout,
|
||||
"headers": headers
|
||||
}
|
||||
|
||||
if self.proxy:
|
||||
args["proxy"] = self.proxy
|
||||
if self.proxy_headers:
|
||||
args["proxy_headers"] = self.proxy_headers
|
||||
|
||||
if query_params:
|
||||
args["url"] += '?' + urlencode(query_params)
|
||||
|
||||
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
|
||||
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
|
||||
if re.search('json', headers['Content-Type'], re.IGNORECASE):
|
||||
if body is not None:
|
||||
body = json.dumps(body)
|
||||
args["data"] = body
|
||||
elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501
|
||||
args["data"] = aiohttp.FormData(post_params)
|
||||
elif headers['Content-Type'] == 'multipart/form-data':
|
||||
# must del headers['Content-Type'], or the correct
|
||||
# Content-Type which generated by aiohttp
|
||||
del headers['Content-Type']
|
||||
data = aiohttp.FormData()
|
||||
for param in post_params:
|
||||
k, v = param
|
||||
if isinstance(v, tuple) and len(v) == 3:
|
||||
data.add_field(k,
|
||||
value=v[1],
|
||||
filename=v[0],
|
||||
content_type=v[2])
|
||||
else:
|
||||
data.add_field(k, v)
|
||||
args["data"] = data
|
||||
|
||||
# Pass a `bytes` parameter directly in the body to support
|
||||
# other content types than Json when `body` argument is provided
|
||||
# in serialized form
|
||||
elif isinstance(body, bytes):
|
||||
args["data"] = body
|
||||
else:
|
||||
# Cannot generate the request from given parameters
|
||||
msg = """Cannot prepare a request message for provided
|
||||
arguments. Please check that your arguments match
|
||||
declared content type."""
|
||||
raise ApiException(status=0, reason=msg)
|
||||
|
||||
r = await self.pool_manager.request(**args)
|
||||
if _preload_content:
|
||||
|
||||
data = await r.read()
|
||||
r = RESTResponse(r, data)
|
||||
|
||||
# log response body
|
||||
logger.debug("response body: %s", r.data)
|
||||
|
||||
if not 200 <= r.status <= 299:
|
||||
raise ApiException(http_resp=r)
|
||||
|
||||
return r
|
||||
|
||||
async def GET(self, url, headers=None, query_params=None,
|
||||
_preload_content=True, _request_timeout=None):
|
||||
return (await self.request("GET", url,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
query_params=query_params))
|
||||
|
||||
async def HEAD(self, url, headers=None, query_params=None,
|
||||
_preload_content=True, _request_timeout=None):
|
||||
return (await self.request("HEAD", url,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
query_params=query_params))
|
||||
|
||||
async def OPTIONS(self, url, headers=None, query_params=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
return (await self.request("OPTIONS", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body))
|
||||
|
||||
async def DELETE(self, url, headers=None, query_params=None, body=None,
|
||||
_preload_content=True, _request_timeout=None):
|
||||
return (await self.request("DELETE", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body))
|
||||
|
||||
async def POST(self, url, headers=None, query_params=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
return (await self.request("POST", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body))
|
||||
|
||||
async def PUT(self, url, headers=None, query_params=None, post_params=None,
|
||||
body=None, _preload_content=True, _request_timeout=None):
|
||||
return (await self.request("PUT", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body))
|
||||
|
||||
async def PATCH(self, url, headers=None, query_params=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
return (await self.request("PATCH", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body))
|
@ -2,6 +2,8 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import copy
|
||||
import logging
|
||||
{{^asyncio}}
|
||||
@ -10,7 +12,8 @@ import multiprocessing
|
||||
import sys
|
||||
import urllib3
|
||||
|
||||
from http import client as http_client
|
||||
import six
|
||||
from six.moves import http_client as httplib
|
||||
from {{packageName}}.exceptions import ApiValueError
|
||||
|
||||
|
||||
@ -299,8 +302,9 @@ conf = {{{packageName}}}.Configuration(
|
||||
# Enable client side validation
|
||||
self.client_side_validation = True
|
||||
|
||||
# Options to pass down to the underlying urllib3 socket
|
||||
self.socket_options = None
|
||||
"""Options to pass down to the underlying urllib3 socket
|
||||
"""
|
||||
|
||||
def __deepcopy__(self, memo):
|
||||
cls = self.__class__
|
||||
@ -385,7 +389,7 @@ conf = {{{packageName}}}.Configuration(
|
||||
# then add file handler and remove stream handler.
|
||||
self.logger_file_handler = logging.FileHandler(self.__logger_file)
|
||||
self.logger_file_handler.setFormatter(self.logger_formatter)
|
||||
for _, logger in self.logger.items():
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
logger.addHandler(self.logger_file_handler)
|
||||
|
||||
@property
|
||||
@ -407,17 +411,17 @@ conf = {{{packageName}}}.Configuration(
|
||||
self.__debug = value
|
||||
if self.__debug:
|
||||
# if debug status is True, turn on debug logging
|
||||
for _, logger in self.logger.items():
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
logger.setLevel(logging.DEBUG)
|
||||
# turn on http_client debug
|
||||
http_client.HTTPConnection.debuglevel = 1
|
||||
# turn on httplib debug
|
||||
httplib.HTTPConnection.debuglevel = 1
|
||||
else:
|
||||
# if debug status is False, turn off debug logging,
|
||||
# setting log level to default `logging.WARNING`
|
||||
for _, logger in self.logger.items():
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
logger.setLevel(logging.WARNING)
|
||||
# turn off http_client debug
|
||||
http_client.HTTPConnection.debuglevel = 0
|
||||
# turn off httplib debug
|
||||
httplib.HTTPConnection.debuglevel = 0
|
||||
|
||||
@property
|
||||
def logger_format(self):
|
@ -2,6 +2,8 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import six
|
||||
|
||||
|
||||
class OpenApiException(Exception):
|
||||
"""The base exception class for all OpenAPIExceptions"""
|
||||
@ -118,11 +120,35 @@ class ApiException(OpenApiException):
|
||||
return error_message
|
||||
|
||||
|
||||
class NotFoundException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(NotFoundException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class UnauthorizedException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(UnauthorizedException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class ForbiddenException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(ForbiddenException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class ServiceException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(ServiceException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
def render_path(path_to_item):
|
||||
"""Returns a string representation of a path"""
|
||||
result = ""
|
||||
for pth in path_to_item:
|
||||
if isinstance(pth, int):
|
||||
if isinstance(pth, six.integer_types):
|
||||
result += "[{0}]".format(pth)
|
||||
else:
|
||||
result += "['{0}']".format(pth)
|
58
modules/openapi-generator/src/main/resources/python-legacy/git_push.sh.mustache
vendored
Executable file
58
modules/openapi-generator/src/main/resources/python-legacy/git_push.sh.mustache
vendored
Executable file
@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
|
||||
#
|
||||
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
|
||||
|
||||
git_user_id=$1
|
||||
git_repo_id=$2
|
||||
release_note=$3
|
||||
git_host=$4
|
||||
|
||||
if [ "$git_host" = "" ]; then
|
||||
git_host="{{{gitHost}}}"
|
||||
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
|
||||
fi
|
||||
|
||||
if [ "$git_user_id" = "" ]; then
|
||||
git_user_id="{{{gitUserId}}}"
|
||||
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
|
||||
fi
|
||||
|
||||
if [ "$git_repo_id" = "" ]; then
|
||||
git_repo_id="{{{gitRepoId}}}"
|
||||
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
|
||||
fi
|
||||
|
||||
if [ "$release_note" = "" ]; then
|
||||
release_note="{{{releaseNote}}}"
|
||||
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
|
||||
fi
|
||||
|
||||
# Initialize the local directory as a Git repository
|
||||
git init
|
||||
|
||||
# Adds the files in the local repository and stages them for commit.
|
||||
git add .
|
||||
|
||||
# Commits the tracked changes and prepares them to be pushed to a remote repository.
|
||||
git commit -m "$release_note"
|
||||
|
||||
# Sets the new remote
|
||||
git_remote=`git remote`
|
||||
if [ "$git_remote" = "" ]; then # git remote not defined
|
||||
|
||||
if [ "$GIT_TOKEN" = "" ]; then
|
||||
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
|
||||
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
|
||||
else
|
||||
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
git pull origin master
|
||||
|
||||
# Pushes (Forces) the changes in the local repository up to the remote repository
|
||||
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
|
||||
git push origin master 2>&1 | grep -v 'To https'
|
||||
|
@ -3,7 +3,7 @@
|
||||
stages:
|
||||
- test
|
||||
|
||||
.tests:
|
||||
.nosetest:
|
||||
stage: test
|
||||
script:
|
||||
- pip install -r requirements.txt
|
||||
@ -15,15 +15,24 @@ stages:
|
||||
- pytest --cov={{{packageName}}}
|
||||
{{/useNose}}
|
||||
|
||||
test-3.5:
|
||||
extends: .tests
|
||||
nosetest-2.7:
|
||||
extends: .nosetest
|
||||
image: python:2.7-alpine
|
||||
nosetest-3.3:
|
||||
extends: .nosetest
|
||||
image: python:3.3-alpine
|
||||
nosetest-3.4:
|
||||
extends: .nosetest
|
||||
image: python:3.4-alpine
|
||||
nosetest-3.5:
|
||||
extends: .nosetest
|
||||
image: python:3.5-alpine
|
||||
test-3.6:
|
||||
extends: .tests
|
||||
nosetest-3.6:
|
||||
extends: .nosetest
|
||||
image: python:3.6-alpine
|
||||
test-3.7:
|
||||
extends: .tests
|
||||
nosetest-3.7:
|
||||
extends: .nosetest
|
||||
image: python:3.7-alpine
|
||||
test-3.8:
|
||||
extends: .tests
|
||||
nosetest-3.8:
|
||||
extends: .nosetest
|
||||
image: python:3.8-alpine
|
254
modules/openapi-generator/src/main/resources/python-legacy/model.mustache
vendored
Normal file
254
modules/openapi-generator/src/main/resources/python-legacy/model.mustache
vendored
Normal file
@ -0,0 +1,254 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import inspect
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import six
|
||||
|
||||
from {{packageName}}.configuration import Configuration
|
||||
|
||||
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
class {{classname}}(object):
|
||||
"""NOTE: This class is auto generated by OpenAPI Generator.
|
||||
Ref: https://openapi-generator.tech
|
||||
|
||||
Do not edit the class manually.
|
||||
"""{{#allowableValues}}
|
||||
|
||||
"""
|
||||
allowed enum values
|
||||
"""
|
||||
{{#enumVars}}
|
||||
{{name}} = {{{value}}}{{^-last}}
|
||||
{{/-last}}
|
||||
{{/enumVars}}{{/allowableValues}}
|
||||
|
||||
{{#allowableValues}}
|
||||
allowable_values = [{{#enumVars}}{{name}}{{^-last}}, {{/-last}}{{/enumVars}}] # noqa: E501
|
||||
|
||||
{{/allowableValues}}
|
||||
"""
|
||||
Attributes:
|
||||
openapi_types (dict): The key is attribute name
|
||||
and the value is attribute type.
|
||||
attribute_map (dict): The key is attribute name
|
||||
and the value is json key in definition.
|
||||
"""
|
||||
openapi_types = {
|
||||
{{#vars}}
|
||||
'{{name}}': '{{{dataType}}}'{{^-last}},{{/-last}}
|
||||
{{/vars}}
|
||||
}
|
||||
|
||||
attribute_map = {
|
||||
{{#vars}}
|
||||
'{{name}}': '{{baseName}}'{{^-last}},{{/-last}}
|
||||
{{/vars}}
|
||||
}
|
||||
{{#discriminator}}
|
||||
|
||||
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}},{{/-last}}
|
||||
{{/children}}
|
||||
}
|
||||
{{/discriminator}}
|
||||
|
||||
def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}, local_vars_configuration=None): # noqa: E501
|
||||
"""{{classname}} - a model defined in OpenAPI""" # noqa: E501
|
||||
if local_vars_configuration is None:
|
||||
local_vars_configuration = Configuration()
|
||||
self.local_vars_configuration = local_vars_configuration
|
||||
{{#vars}}{{#-first}}
|
||||
{{/-first}}
|
||||
self._{{name}} = None
|
||||
{{/vars}}
|
||||
self.discriminator = {{#discriminator}}'{{{discriminatorName}}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}}
|
||||
{{#vars}}{{#-first}}
|
||||
{{/-first}}
|
||||
{{#required}}
|
||||
self.{{name}} = {{name}}
|
||||
{{/required}}
|
||||
{{^required}}
|
||||
{{#isNullable}}
|
||||
self.{{name}} = {{name}}
|
||||
{{/isNullable}}
|
||||
{{^isNullable}}
|
||||
if {{name}} is not None:
|
||||
self.{{name}} = {{name}}
|
||||
{{/isNullable}}
|
||||
{{/required}}
|
||||
{{/vars}}
|
||||
|
||||
{{#vars}}
|
||||
@property
|
||||
def {{name}}(self):
|
||||
"""Gets the {{name}} of this {{classname}}. # noqa: E501
|
||||
|
||||
{{#description}}
|
||||
{{{description}}} # noqa: E501
|
||||
{{/description}}
|
||||
|
||||
:return: The {{name}} of this {{classname}}. # noqa: E501
|
||||
:rtype: {{dataType}}
|
||||
"""
|
||||
return self._{{name}}
|
||||
|
||||
@{{name}}.setter
|
||||
def {{name}}(self, {{name}}):
|
||||
"""Sets the {{name}} of this {{classname}}.
|
||||
|
||||
{{#description}}
|
||||
{{{description}}} # noqa: E501
|
||||
{{/description}}
|
||||
|
||||
:param {{name}}: The {{name}} of this {{classname}}. # noqa: E501
|
||||
:type {{name}}: {{dataType}}
|
||||
"""
|
||||
{{^isNullable}}
|
||||
{{#required}}
|
||||
if self.local_vars_configuration.client_side_validation and {{name}} is None: # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501
|
||||
{{/required}}
|
||||
{{/isNullable}}
|
||||
{{#isEnum}}
|
||||
{{#isContainer}}
|
||||
allowed_values = [{{#isNullable}}None,{{/isNullable}}{{#allowableValues}}{{#values}}{{#items.isString}}"{{/items.isString}}{{{this}}}{{#items.isString}}"{{/items.isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501
|
||||
{{#isArray}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
not set({{{name}}}).issubset(set(allowed_values))): # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501
|
||||
.format(", ".join(map(str, set({{{name}}}) - set(allowed_values))), # noqa: E501
|
||||
", ".join(map(str, allowed_values)))
|
||||
)
|
||||
{{/isArray}}
|
||||
{{#isMap}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
not set({{{name}}}.keys()).issubset(set(allowed_values))): # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501
|
||||
.format(", ".join(map(str, set({{{name}}}.keys()) - set(allowed_values))), # noqa: E501
|
||||
", ".join(map(str, allowed_values)))
|
||||
)
|
||||
{{/isMap}}
|
||||
{{/isContainer}}
|
||||
{{^isContainer}}
|
||||
allowed_values = [{{#isNullable}}None,{{/isNullable}}{{#allowableValues}}{{#values}}{{#isString}}"{{/isString}}{{{this}}}{{#isString}}"{{/isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501
|
||||
if self.local_vars_configuration.client_side_validation and {{{name}}} not in allowed_values: # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid value for `{{{name}}}` ({0}), must be one of {1}" # noqa: E501
|
||||
.format({{{name}}}, allowed_values)
|
||||
)
|
||||
{{/isContainer}}
|
||||
{{/isEnum}}
|
||||
{{^isEnum}}
|
||||
{{#hasValidation}}
|
||||
{{#maxLength}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) > {{maxLength}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501
|
||||
{{/maxLength}}
|
||||
{{#minLength}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) < {{minLength}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501
|
||||
{{/minLength}}
|
||||
{{#maximum}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}): # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501
|
||||
{{/maximum}}
|
||||
{{#minimum}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}): # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501
|
||||
{{/minimum}}
|
||||
{{#pattern}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and not re.search(r'{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}})): # noqa: E501
|
||||
raise ValueError(r"Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") # noqa: E501
|
||||
{{/pattern}}
|
||||
{{#maxItems}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) > {{maxItems}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501
|
||||
{{/maxItems}}
|
||||
{{#minItems}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) < {{minItems}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501
|
||||
{{/minItems}}
|
||||
{{/hasValidation}}
|
||||
{{/isEnum}}
|
||||
|
||||
self._{{name}} = {{name}}
|
||||
|
||||
{{/vars}}
|
||||
{{#discriminator}}
|
||||
def get_real_child_model(self, data):
|
||||
"""Returns the real base class specified by the discriminator"""
|
||||
discriminator_key = self.attribute_map[self.discriminator]
|
||||
discriminator_value = data[discriminator_key]
|
||||
return self.discriminator_value_class_map.get(discriminator_value)
|
||||
|
||||
{{/discriminator}}
|
||||
def to_dict(self, serialize=False):
|
||||
"""Returns the model properties as a dict"""
|
||||
result = {}
|
||||
|
||||
def convert(x):
|
||||
if hasattr(x, "to_dict"):
|
||||
args = inspect.getargspec(x.to_dict).args
|
||||
if len(args) == 1:
|
||||
return x.to_dict()
|
||||
else:
|
||||
return x.to_dict(serialize)
|
||||
else:
|
||||
return x
|
||||
|
||||
for attr, _ in six.iteritems(self.openapi_types):
|
||||
value = getattr(self, attr)
|
||||
attr = self.attribute_map.get(attr, attr) if serialize else attr
|
||||
if isinstance(value, list):
|
||||
result[attr] = list(map(
|
||||
lambda x: convert(x),
|
||||
value
|
||||
))
|
||||
elif isinstance(value, dict):
|
||||
result[attr] = dict(map(
|
||||
lambda item: (item[0], convert(item[1])),
|
||||
value.items()
|
||||
))
|
||||
else:
|
||||
result[attr] = convert(value)
|
||||
|
||||
return result
|
||||
|
||||
def to_str(self):
|
||||
"""Returns the string representation of the model"""
|
||||
return pprint.pformat(self.to_dict())
|
||||
|
||||
def __repr__(self):
|
||||
"""For `print` and `pprint`"""
|
||||
return self.to_str()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Returns true if both objects are equal"""
|
||||
if not isinstance(other, {{classname}}):
|
||||
return False
|
||||
|
||||
return self.to_dict() == other.to_dict()
|
||||
|
||||
def __ne__(self, other):
|
||||
"""Returns true if both objects are not equal"""
|
||||
if not isinstance(other, {{classname}}):
|
||||
return True
|
||||
|
||||
return self.to_dict() != other.to_dict()
|
||||
{{/model}}
|
||||
{{/models}}
|
13
modules/openapi-generator/src/main/resources/python-legacy/model_doc.mustache
vendored
Normal file
13
modules/openapi-generator/src/main/resources/python-legacy/model_doc.mustache
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
{{#models}}{{#model}}# {{classname}}
|
||||
|
||||
{{#description}}{{&description}}
|
||||
{{/description}}
|
||||
## Properties
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
|
||||
{{/vars}}
|
||||
|
||||
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
||||
|
||||
{{/model}}{{/models}}
|
64
modules/openapi-generator/src/main/resources/python-legacy/model_test.mustache
vendored
Normal file
64
modules/openapi-generator/src/main/resources/python-legacy/model_test.mustache
vendored
Normal file
@ -0,0 +1,64 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import unittest
|
||||
import datetime
|
||||
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
import {{packageName}}
|
||||
from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501
|
||||
from {{packageName}}.rest import ApiException
|
||||
|
||||
class Test{{classname}}(unittest.TestCase):
|
||||
"""{{classname}} unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
{{^interfaces}}
|
||||
|
||||
def make_instance(self, include_optional):
|
||||
"""Test {{classname}}
|
||||
include_option is a boolean, when False only required
|
||||
params are included, when True both required and
|
||||
optional params are included """
|
||||
# model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501
|
||||
if include_optional :
|
||||
return {{classname}}(
|
||||
{{#vars}}
|
||||
{{name}} = {{#example}}{{{.}}}{{/example}}{{^example}}None{{/example}}{{^-last}}, {{/-last}}
|
||||
{{/vars}}
|
||||
)
|
||||
else :
|
||||
return {{classname}}(
|
||||
{{#vars}}
|
||||
{{#required}}
|
||||
{{name}} = {{#example}}{{{.}}}{{/example}}{{^example}}None{{/example}},
|
||||
{{/required}}
|
||||
{{/vars}}
|
||||
)
|
||||
{{/interfaces}}
|
||||
|
||||
def test{{classname}}(self):
|
||||
"""Test {{classname}}"""
|
||||
{{^interfaces}}
|
||||
inst_req_only = self.make_instance(include_optional=False)
|
||||
inst_req_and_optional = self.make_instance(include_optional=True)
|
||||
{{/interfaces}}
|
||||
{{#interfaces}}
|
||||
{{#-last}}
|
||||
# inst_req_only = self.make_instance(include_optional=False)
|
||||
# inst_req_and_optional = self.make_instance(include_optional=True)
|
||||
{{/-last}}
|
||||
{{/interfaces}}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
17
modules/openapi-generator/src/main/resources/python-legacy/partial_header.mustache
vendored
Normal file
17
modules/openapi-generator/src/main/resources/python-legacy/partial_header.mustache
vendored
Normal file
@ -0,0 +1,17 @@
|
||||
"""
|
||||
{{#appName}}
|
||||
{{{appName}}}
|
||||
{{/appName}}
|
||||
|
||||
{{#appDescription}}
|
||||
{{{appDescription}}} # noqa: E501
|
||||
{{/appDescription}}
|
||||
|
||||
{{#version}}
|
||||
The version of the OpenAPI document: {{{version}}}
|
||||
{{/version}}
|
||||
{{#infoEmail}}
|
||||
Contact: {{{infoEmail}}}
|
||||
{{/infoEmail}}
|
||||
Generated by: https://openapi-generator.tech
|
||||
"""
|
109
modules/openapi-generator/src/main/resources/python-legacy/python_doc_auth_partial.mustache
vendored
Normal file
109
modules/openapi-generator/src/main/resources/python-legacy/python_doc_auth_partial.mustache
vendored
Normal file
@ -0,0 +1,109 @@
|
||||
# Defining the host is optional and defaults to {{{basePath}}}
|
||||
# See configuration.py for a list of all supported configuration parameters.
|
||||
configuration = {{{packageName}}}.Configuration(
|
||||
host = "{{{basePath}}}"
|
||||
)
|
||||
|
||||
{{#hasAuthMethods}}
|
||||
# The client must configure the authentication and authorization parameters
|
||||
# in accordance with the API server security policy.
|
||||
# Examples for each auth method are provided below, use the example that
|
||||
# satisfies your auth use case.
|
||||
{{#authMethods}}
|
||||
{{#isBasic}}
|
||||
{{#isBasicBasic}}
|
||||
|
||||
# Configure HTTP basic authorization: {{{name}}}
|
||||
configuration = {{{packageName}}}.Configuration(
|
||||
username = 'YOUR_USERNAME',
|
||||
password = 'YOUR_PASSWORD'
|
||||
)
|
||||
{{/isBasicBasic}}
|
||||
{{#isBasicBearer}}
|
||||
|
||||
# Configure Bearer authorization{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}: {{{name}}}
|
||||
configuration = {{{packageName}}}.Configuration(
|
||||
access_token = 'YOUR_BEARER_TOKEN'
|
||||
)
|
||||
{{/isBasicBearer}}
|
||||
{{#isHttpSignature}}
|
||||
|
||||
# Configure HTTP message signature: {{{name}}}
|
||||
# The HTTP Signature Header mechanism that can be used by a client to
|
||||
# authenticate the sender of a message and ensure that particular headers
|
||||
# have not been modified in transit.
|
||||
#
|
||||
# You can specify the signing key-id, private key path, signing scheme,
|
||||
# signing algorithm, list of signed headers and signature max validity.
|
||||
# The 'key_id' parameter is an opaque string that the API server can use
|
||||
# to lookup the client and validate the signature.
|
||||
# The 'private_key_path' parameter should be the path to a file that
|
||||
# contains a DER or base-64 encoded private key.
|
||||
# The 'private_key_passphrase' parameter is optional. Set the passphrase
|
||||
# if the private key is encrypted.
|
||||
# The 'signed_headers' parameter is used to specify the list of
|
||||
# HTTP headers included when generating the signature for the message.
|
||||
# You can specify HTTP headers that you want to protect with a cryptographic
|
||||
# signature. Note that proxies may add, modify or remove HTTP headers
|
||||
# for legitimate reasons, so you should only add headers that you know
|
||||
# will not be modified. For example, if you want to protect the HTTP request
|
||||
# body, you can specify the Digest header. In that case, the client calculates
|
||||
# the digest of the HTTP request body and includes the digest in the message
|
||||
# signature.
|
||||
# The 'signature_max_validity' parameter is optional. It is configured as a
|
||||
# duration to express when the signature ceases to be valid. The client calculates
|
||||
# the expiration date every time it generates the cryptographic signature
|
||||
# of an HTTP request. The API server may have its own security policy
|
||||
# that controls the maximum validity of the signature. The client max validity
|
||||
# must be lower than the server max validity.
|
||||
# The time on the client and server must be synchronized, otherwise the
|
||||
# server may reject the client signature.
|
||||
#
|
||||
# The client must use a combination of private key, signing scheme,
|
||||
# signing algorithm and hash algorithm that matches the security policy of
|
||||
# the API server.
|
||||
#
|
||||
# See {{{packageName}}}.signing for a list of all supported parameters.
|
||||
configuration = {{{packageName}}}.Configuration(
|
||||
host = "{{{basePath}}}",
|
||||
signing_info = {{{packageName}}}.signing.HttpSigningConfiguration(
|
||||
key_id = 'my-key-id',
|
||||
private_key_path = 'private_key.pem',
|
||||
private_key_passphrase = 'YOUR_PASSPHRASE',
|
||||
signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019,
|
||||
signing_algorithm = {{{packageName}}}.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3,
|
||||
hash_algorithm = {{{packageName}}}.signing.SCHEME_RSA_SHA256,
|
||||
signed_headers = [
|
||||
{{{packageName}}}.signing.HEADER_REQUEST_TARGET,
|
||||
{{{packageName}}}.signing.HEADER_CREATED,
|
||||
{{{packageName}}}.signing.HEADER_EXPIRES,
|
||||
{{{packageName}}}.signing.HEADER_HOST,
|
||||
{{{packageName}}}.signing.HEADER_DATE,
|
||||
{{{packageName}}}.signing.HEADER_DIGEST,
|
||||
'Content-Type',
|
||||
'Content-Length',
|
||||
'User-Agent'
|
||||
],
|
||||
signature_max_validity = datetime.timedelta(minutes=5)
|
||||
)
|
||||
)
|
||||
{{/isHttpSignature}}
|
||||
{{/isBasic}}
|
||||
{{#isApiKey}}
|
||||
|
||||
# Configure API key authorization: {{{name}}}
|
||||
configuration.api_key['{{{name}}}'] = 'YOUR_API_KEY'
|
||||
|
||||
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
|
||||
# configuration.api_key_prefix['{{name}}'] = 'Bearer'
|
||||
{{/isApiKey}}
|
||||
{{#isOAuth}}
|
||||
|
||||
# Configure OAuth2 access token for authorization: {{{name}}}
|
||||
configuration = {{{packageName}}}.Configuration(
|
||||
host = "{{{basePath}}}"
|
||||
)
|
||||
configuration.access_token = 'YOUR_ACCESS_TOKEN'
|
||||
{{/isOAuth}}
|
||||
{{/authMethods}}
|
||||
{{/hasAuthMethods}}
|
@ -1,5 +1,6 @@
|
||||
nulltype
|
||||
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
|
@ -2,17 +2,21 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import ssl
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import certifi
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
from six.moves.urllib.parse import urlencode
|
||||
import urllib3
|
||||
|
||||
from {{packageName}}.exceptions import ApiException, ApiValueError
|
||||
from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -132,7 +136,7 @@ class RESTClientObject(object):
|
||||
|
||||
timeout = None
|
||||
if _request_timeout:
|
||||
if isinstance(_request_timeout, (int, float)): # noqa: E501,F821
|
||||
if isinstance(_request_timeout, six.integer_types + (float, )): # noqa: E501,F821
|
||||
timeout = urllib3.Timeout(total=_request_timeout)
|
||||
elif (isinstance(_request_timeout, tuple) and
|
||||
len(_request_timeout) == 2):
|
||||
@ -212,6 +216,18 @@ class RESTClientObject(object):
|
||||
logger.debug("response body: %s", r.data)
|
||||
|
||||
if not 200 <= r.status <= 299:
|
||||
if r.status == 401:
|
||||
raise UnauthorizedException(http_resp=r)
|
||||
|
||||
if r.status == 403:
|
||||
raise ForbiddenException(http_resp=r)
|
||||
|
||||
if r.status == 404:
|
||||
raise NotFoundException(http_resp=r)
|
||||
|
||||
if 500 <= r.status <= 599:
|
||||
raise ServiceException(http_resp=r)
|
||||
|
||||
raise ApiException(http_resp=r)
|
||||
|
||||
return r
|
@ -16,22 +16,13 @@ VERSION = "{{packageVersion}}"
|
||||
# prerequisite: setuptools
|
||||
# http://pypi.python.org/pypi/setuptools
|
||||
|
||||
REQUIRES = [
|
||||
"urllib3 >= 1.15",
|
||||
"certifi",
|
||||
"python-dateutil",
|
||||
"nulltype",
|
||||
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"]
|
||||
{{#asyncio}}
|
||||
"aiohttp >= 3.0.0",
|
||||
REQUIRES.append("aiohttp >= 3.0.0")
|
||||
{{/asyncio}}
|
||||
{{#tornado}}
|
||||
"tornado>=4.2,<5",
|
||||
REQUIRES.append("tornado>=4.2,<5")
|
||||
{{/tornado}}
|
||||
{{#hasHttpSignatureMethods}}
|
||||
"pem>=19.3.0",
|
||||
"pycryptodome>=3.9.0",
|
||||
{{/hasHttpSignatureMethods}}
|
||||
]
|
||||
|
||||
setup(
|
||||
name=NAME,
|
||||
@ -41,7 +32,6 @@ setup(
|
||||
author_email="{{#infoEmail}}{{infoEmail}}{{/infoEmail}}{{^infoEmail}}team@openapitools.org{{/infoEmail}}",
|
||||
url="{{packageUrl}}",
|
||||
keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"],
|
||||
python_requires=">=3.5",
|
||||
install_requires=REQUIRES,
|
||||
packages=find_packages(exclude=["test", "tests"]),
|
||||
include_package_data=True,
|
13
modules/openapi-generator/src/main/resources/python-legacy/setup_cfg.mustache
vendored
Normal file
13
modules/openapi-generator/src/main/resources/python-legacy/setup_cfg.mustache
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
{{#useNose}}
|
||||
[nosetests]
|
||||
logging-clear-handlers=true
|
||||
verbosity=2
|
||||
randomize=true
|
||||
exe=true
|
||||
with-coverage=true
|
||||
cover-package={{{packageName}}}
|
||||
cover-erase=true
|
||||
|
||||
{{/useNose}}
|
||||
[flake8]
|
||||
max-line-length=99
|
12
modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache
vendored
Normal file
12
modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache
vendored
Normal file
@ -0,0 +1,12 @@
|
||||
{{#useNose}}
|
||||
coverage>=4.0.3
|
||||
nose>=1.3.7
|
||||
pluggy>=0.3.1
|
||||
py>=1.4.31
|
||||
randomize>=0.13
|
||||
{{/useNose}}
|
||||
{{^useNose}}
|
||||
pytest~=4.6.7 # needed for python 2.7+3.4
|
||||
pytest-cov>=2.8.1
|
||||
pytest-randomly==1.2.3 # needed for python 2.7+3.4
|
||||
{{/useNose}}
|
224
modules/openapi-generator/src/main/resources/python-legacy/tornado/rest.mustache
vendored
Normal file
224
modules/openapi-generator/src/main/resources/python-legacy/tornado/rest.mustache
vendored
Normal file
@ -0,0 +1,224 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
# python 2 and python 3 compatibility library
|
||||
from six.moves.urllib.parse import urlencode
|
||||
import tornado
|
||||
import tornado.gen
|
||||
from tornado import httpclient
|
||||
from urllib3.filepost import encode_multipart_formdata
|
||||
|
||||
from {{packageName}}.exceptions import ApiException, ApiValueError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RESTResponse(io.IOBase):
|
||||
|
||||
def __init__(self, resp):
|
||||
self.tornado_response = resp
|
||||
self.status = resp.code
|
||||
self.reason = resp.reason
|
||||
|
||||
if resp.body:
|
||||
self.data = resp.body
|
||||
else:
|
||||
self.data = None
|
||||
|
||||
def getheaders(self):
|
||||
"""Returns a CIMultiDictProxy of the response headers."""
|
||||
return self.tornado_response.headers
|
||||
|
||||
def getheader(self, name, default=None):
|
||||
"""Returns a given response header."""
|
||||
return self.tornado_response.headers.get(name, default)
|
||||
|
||||
|
||||
class RESTClientObject(object):
|
||||
|
||||
def __init__(self, configuration, pools_size=4, maxsize=4):
|
||||
# maxsize is number of requests to host that are allowed in parallel
|
||||
|
||||
self.ca_certs = configuration.ssl_ca_cert
|
||||
self.client_key = configuration.key_file
|
||||
self.client_cert = configuration.cert_file
|
||||
|
||||
self.proxy_port = self.proxy_host = None
|
||||
|
||||
# https pool manager
|
||||
if configuration.proxy:
|
||||
self.proxy_port = 80
|
||||
self.proxy_host = configuration.proxy
|
||||
|
||||
self.pool_manager = httpclient.AsyncHTTPClient()
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def request(self, method, url, query_params=None, headers=None, body=None,
|
||||
post_params=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
"""Execute Request
|
||||
|
||||
:param method: http request method
|
||||
:param url: http request url
|
||||
:param query_params: query parameters in the url
|
||||
:param headers: http request headers
|
||||
:param body: request json body, for `application/json`
|
||||
:param post_params: request post parameters,
|
||||
`application/x-www-form-urlencoded`
|
||||
and `multipart/form-data`
|
||||
:param _preload_content: this is a non-applicable field for
|
||||
the AiohttpClient.
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
"""
|
||||
method = method.upper()
|
||||
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT',
|
||||
'PATCH', 'OPTIONS']
|
||||
|
||||
if post_params and body:
|
||||
raise ApiValueError(
|
||||
"body parameter cannot be used with post_params parameter."
|
||||
)
|
||||
|
||||
request = httpclient.HTTPRequest(url)
|
||||
request.allow_nonstandard_methods = True
|
||||
request.ca_certs = self.ca_certs
|
||||
request.client_key = self.client_key
|
||||
request.client_cert = self.client_cert
|
||||
request.proxy_host = self.proxy_host
|
||||
request.proxy_port = self.proxy_port
|
||||
request.method = method
|
||||
if headers:
|
||||
request.headers = headers
|
||||
if 'Content-Type' not in headers:
|
||||
request.headers['Content-Type'] = 'application/json'
|
||||
request.request_timeout = _request_timeout or 5 * 60
|
||||
|
||||
post_params = post_params or {}
|
||||
|
||||
if query_params:
|
||||
request.url += '?' + urlencode(query_params)
|
||||
|
||||
# For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE`
|
||||
if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']:
|
||||
if re.search('json', headers['Content-Type'], re.IGNORECASE):
|
||||
if body:
|
||||
body = json.dumps(body)
|
||||
request.body = body
|
||||
elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501
|
||||
request.body = urlencode(post_params)
|
||||
elif headers['Content-Type'] == 'multipart/form-data':
|
||||
multipart = encode_multipart_formdata(post_params)
|
||||
request.body, headers['Content-Type'] = multipart
|
||||
# Pass a `bytes` parameter directly in the body to support
|
||||
# other content types than Json when `body` argument is provided
|
||||
# in serialized form
|
||||
elif isinstance(body, bytes):
|
||||
request.body = body
|
||||
else:
|
||||
# Cannot generate the request from given parameters
|
||||
msg = """Cannot prepare a request message for provided
|
||||
arguments. Please check that your arguments match
|
||||
declared content type."""
|
||||
raise ApiException(status=0, reason=msg)
|
||||
|
||||
r = yield self.pool_manager.fetch(request, raise_error=False)
|
||||
|
||||
if _preload_content:
|
||||
|
||||
r = RESTResponse(r)
|
||||
|
||||
# log response body
|
||||
logger.debug("response body: %s", r.data)
|
||||
|
||||
if not 200 <= r.status <= 299:
|
||||
raise ApiException(http_resp=r)
|
||||
|
||||
raise tornado.gen.Return(r)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def GET(self, url, headers=None, query_params=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
result = yield self.request("GET", url,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
query_params=query_params)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def HEAD(self, url, headers=None, query_params=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
result = yield self.request("HEAD", url,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
query_params=query_params)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def OPTIONS(self, url, headers=None, query_params=None, post_params=None,
|
||||
body=None, _preload_content=True, _request_timeout=None):
|
||||
result = yield self.request("OPTIONS", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def DELETE(self, url, headers=None, query_params=None, body=None,
|
||||
_preload_content=True, _request_timeout=None):
|
||||
result = yield self.request("DELETE", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def POST(self, url, headers=None, query_params=None, post_params=None,
|
||||
body=None, _preload_content=True, _request_timeout=None):
|
||||
result = yield self.request("POST", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def PUT(self, url, headers=None, query_params=None, post_params=None,
|
||||
body=None, _preload_content=True, _request_timeout=None):
|
||||
result = yield self.request("PUT", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
raise tornado.gen.Return(result)
|
||||
|
||||
@tornado.gen.coroutine
|
||||
def PATCH(self, url, headers=None, query_params=None, post_params=None,
|
||||
body=None, _preload_content=True, _request_timeout=None):
|
||||
result = yield self.request("PATCH", url,
|
||||
headers=headers,
|
||||
query_params=query_params,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
raise tornado.gen.Return(result)
|
@ -1,5 +1,10 @@
|
||||
[tox]
|
||||
{{^asyncio}}
|
||||
envlist = py27, py3
|
||||
{{/asyncio}}
|
||||
{{#asyncio}}
|
||||
envlist = py3
|
||||
{{/asyncio}}
|
||||
|
||||
[testenv]
|
||||
deps=-r{toxinidir}/requirements.txt
|
@ -1,6 +1,10 @@
|
||||
# ref: https://docs.travis-ci.com/user/languages/python
|
||||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
- "3.2"
|
||||
- "3.3"
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
- "3.7"
|
@ -17,7 +17,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
||||
|
||||
## Requirements.
|
||||
|
||||
Python 2.7 and 3.4+
|
||||
Python >= 3.5
|
||||
|
||||
## Installation & Usage
|
||||
### pip install
|
||||
@ -52,4 +52,4 @@ import {{{packageName}}}
|
||||
|
||||
Please follow the [installation procedure](#installation--usage) and then run the following:
|
||||
|
||||
{{> common_README }}
|
||||
{{> README_common }}
|
||||
|
@ -17,7 +17,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
|
||||
|
||||
## Requirements.
|
||||
|
||||
Python 2.7 and 3.4+
|
||||
Python >= 3.5
|
||||
|
||||
## Installation & Usage
|
||||
|
||||
@ -26,7 +26,6 @@ This python library package is generated without supporting files like setup.py
|
||||
To be able to use it, you will need these dependencies in your own package that uses this library:
|
||||
|
||||
* urllib3 >= 1.15
|
||||
* six >= 1.10
|
||||
* certifi
|
||||
* python-dateutil
|
||||
{{#asyncio}}
|
||||
@ -41,4 +40,4 @@ To be able to use it, you will need these dependencies in your own package that
|
||||
In your own code, to use this library to connect and interact with {{{projectName}}},
|
||||
you can run the following:
|
||||
|
||||
{{> common_README }}
|
||||
{{> README_common }}
|
||||
|
@ -1,7 +1,9 @@
|
||||
from __future__ import absolute_import
|
||||
|
||||
# flake8: noqa
|
||||
|
||||
# import apis into api package
|
||||
{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}}
|
||||
{{/apis}}{{/apiInfo}}
|
||||
{{#apiInfo}}
|
||||
{{#apis}}
|
||||
{{#-first}}
|
||||
# do not import all apis into this module because that uses a lot of memory and stack frames
|
||||
# if you need the ability to import all apis from one package, import them with
|
||||
# from {{packageName}}.apis import {{classname}}
|
||||
{{/-first}}
|
||||
{{/apis}}
|
||||
{{/apiInfo}}
|
||||
|
@ -1,10 +1,5 @@
|
||||
# coding: utf-8
|
||||
|
||||
# flake8: noqa
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
# import models into model package
|
||||
{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}{{/model}}
|
||||
{{/models}}
|
||||
# we can not import model classes here because that would create a circular
|
||||
# reference which would not work in python2
|
||||
# do not import all models into this module because that uses a lot of memory and stack frames
|
||||
# if you need the ability to import all models from one package, import them with
|
||||
# from {{packageName}.models import ModelA, ModelB
|
||||
|
@ -4,25 +4,24 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
__version__ = "{{packageVersion}}"
|
||||
|
||||
# import apis into sdk package
|
||||
{{#apiInfo}}{{#apis}}from {{apiPackage}}.{{classVarName}} import {{classname}}
|
||||
{{/apis}}{{/apiInfo}}
|
||||
# import ApiClient
|
||||
from {{packageName}}.api_client import ApiClient
|
||||
|
||||
# import Configuration
|
||||
from {{packageName}}.configuration import Configuration
|
||||
{{#hasHttpSignatureMethods}}
|
||||
from {{packageName}}.signing import HttpSigningConfiguration
|
||||
{{/hasHttpSignatureMethods}}
|
||||
|
||||
# import exceptions
|
||||
from {{packageName}}.exceptions import OpenApiException
|
||||
from {{packageName}}.exceptions import ApiAttributeError
|
||||
from {{packageName}}.exceptions import ApiTypeError
|
||||
from {{packageName}}.exceptions import ApiValueError
|
||||
from {{packageName}}.exceptions import ApiKeyError
|
||||
from {{packageName}}.exceptions import ApiAttributeError
|
||||
from {{packageName}}.exceptions import ApiException
|
||||
# import models into sdk package
|
||||
{{#models}}{{#model}}from {{modelPackage}}.{{classFilename}} import {{classname}}
|
||||
{{/model}}{{/models}}
|
||||
{{#recursionLimit}}
|
||||
|
||||
__import__('sys').setrecursionlimit({{{.}}})
|
||||
|
@ -2,18 +2,22 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import re # noqa: F401
|
||||
import sys # noqa: F401
|
||||
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
|
||||
from {{packageName}}.api_client import ApiClient
|
||||
from {{packageName}}.exceptions import ( # noqa: F401
|
||||
ApiTypeError,
|
||||
ApiValueError
|
||||
from {{packageName}}.api_client import ApiClient, Endpoint
|
||||
from {{packageName}}.model_utils import ( # noqa: F401
|
||||
check_allowed_values,
|
||||
check_validations,
|
||||
date,
|
||||
datetime,
|
||||
file_type,
|
||||
none_type,
|
||||
validate_and_convert_types
|
||||
)
|
||||
{{#imports}}
|
||||
{{{import}}}
|
||||
{{/imports}}
|
||||
|
||||
|
||||
{{#operations}}
|
||||
@ -30,265 +34,275 @@ class {{classname}}(object):
|
||||
self.api_client = api_client
|
||||
{{#operation}}
|
||||
|
||||
def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
def __{{operationId}}(
|
||||
self,
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}},
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{#defaultValue}}
|
||||
{{paramName}}={{{defaultValue}}},
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
**kwargs
|
||||
):
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
|
||||
{{#notes}}
|
||||
{{{notes}}} # noqa: E501
|
||||
{{{notes}}} # noqa: E501
|
||||
{{/notes}}
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
|
||||
{{#sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
{{^sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
>>> result = thread.get()
|
||||
>>> thread = api.{{operationId}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}}{{paramName}}={{{defaultValue}}}, {{/defaultValue}}{{/requiredParams}}async_req=True)
|
||||
>>> result = thread.get()
|
||||
|
||||
{{#allParams}}
|
||||
:param {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
|
||||
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
|
||||
{{/allParams}}
|
||||
:param async_req: Whether to execute the request asynchronously.
|
||||
:type async_req: bool, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:return: Returns the result object.
|
||||
If the method is called asynchronously,
|
||||
returns the request thread.
|
||||
:rtype: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
"""
|
||||
kwargs['_return_http_data_only'] = True
|
||||
return self.{{operationId}}_with_http_info({{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs) # noqa: E501
|
||||
{{#requiredParams}}
|
||||
{{#-last}}
|
||||
Args:
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}{{/description}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{#defaultValue}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}]
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
|
||||
def {{operationId}}_with_http_info(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): # noqa: E501
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
Keyword Args:{{#optionalParams}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}}{{/optionalParams}}
|
||||
_return_http_data_only (bool): response data without head status
|
||||
code and headers. Default is True.
|
||||
_preload_content (bool): if False, the urllib3.HTTPResponse object
|
||||
will be returned without reading/decoding response data.
|
||||
Default is True.
|
||||
_request_timeout (float/tuple): timeout setting for this request. If one
|
||||
number provided, it will be total request timeout. It can also
|
||||
be a pair (tuple) of (connection, read) timeouts.
|
||||
Default is None.
|
||||
_check_input_type (bool): specifies if type checking
|
||||
should be done one the data sent to the server.
|
||||
Default is True.
|
||||
_check_return_type (bool): specifies if type checking
|
||||
should be done one the data received from the server.
|
||||
Default is True.
|
||||
_host_index (int/None): specifies the index of the server
|
||||
that we want to use.
|
||||
Default is read from the configuration.
|
||||
async_req (bool): execute request asynchronously
|
||||
|
||||
{{#notes}}
|
||||
{{{notes}}} # noqa: E501
|
||||
{{/notes}}
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
Returns:
|
||||
{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
If the method is called asynchronously, returns the request
|
||||
thread.
|
||||
"""
|
||||
kwargs['async_req'] = kwargs.get(
|
||||
'async_req', False
|
||||
)
|
||||
kwargs['_return_http_data_only'] = kwargs.get(
|
||||
'_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')
|
||||
{{#requiredParams}}
|
||||
kwargs['{{paramName}}'] = \
|
||||
{{paramName}}
|
||||
{{/requiredParams}}
|
||||
return self.call_with_http_info(**kwargs)
|
||||
|
||||
{{#sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
{{^sortParamsByRequiredFlag}}
|
||||
>>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}={{paramName}}_value, {{/required}}{{/allParams}}async_req=True)
|
||||
{{/sortParamsByRequiredFlag}}
|
||||
>>> result = thread.get()
|
||||
|
||||
{{#allParams}}
|
||||
:param {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
|
||||
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
|
||||
{{/allParams}}
|
||||
:param async_req: Whether to execute the request asynchronously.
|
||||
:type async_req: bool, optional
|
||||
:param _return_http_data_only: response data without head status code
|
||||
and headers
|
||||
:type _return_http_data_only: bool, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the authentication
|
||||
in the spec for a single request.
|
||||
:type _request_auth: dict, optional
|
||||
:return: Returns the result object.
|
||||
If the method is called asynchronously,
|
||||
returns the request thread.
|
||||
:rtype: {{#returnType}}tuple({{returnType}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
"""
|
||||
|
||||
{{#servers.0}}
|
||||
local_var_hosts = [
|
||||
self.{{operationId}} = Endpoint(
|
||||
settings={
|
||||
'response_type': {{#returnType}}({{{returnType}}},){{/returnType}}{{^returnType}}None{{/returnType}},
|
||||
{{#authMethods}}
|
||||
{{#-first}}
|
||||
'auth': [
|
||||
{{/-first}}
|
||||
'{{name}}'{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
],
|
||||
{{/-last}}
|
||||
{{/authMethods}}
|
||||
{{^authMethods}}
|
||||
'auth': [],
|
||||
{{/authMethods}}
|
||||
'endpoint_path': '{{{path}}}',
|
||||
'operation_id': '{{operationId}}',
|
||||
'http_method': '{{httpMethod}}',
|
||||
{{#servers}}
|
||||
'{{{url}}}'{{^-last}},{{/-last}}
|
||||
{{#-first}}
|
||||
'servers': [
|
||||
{{/-first}}
|
||||
{
|
||||
'url': "{{{url}}}",
|
||||
'description': "{{{description}}}{{^description}}No description provided{{/description}}",
|
||||
{{#variables}}
|
||||
{{#-first}}
|
||||
'variables': {
|
||||
{{/-first}}
|
||||
'{{{name}}}': {
|
||||
'description': "{{{description}}}{{^description}}No description provided{{/description}}",
|
||||
'default_value': "{{{defaultValue}}}",
|
||||
{{#enumValues}}
|
||||
{{#-first}}
|
||||
'enum_values': [
|
||||
{{/-first}}
|
||||
"{{{.}}}"{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
]
|
||||
{{/-last}}
|
||||
{{/enumValues}}
|
||||
}{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
}
|
||||
{{/-last}}
|
||||
{{/variables}}
|
||||
},
|
||||
{{#-last}}
|
||||
]
|
||||
{{/-last}}
|
||||
{{/servers}}
|
||||
]
|
||||
local_var_host = local_var_hosts[0]
|
||||
if kwargs.get('_host_index'):
|
||||
_host_index = int(kwargs.get('_host_index'))
|
||||
if _host_index < 0 or _host_index >= len(local_var_hosts):
|
||||
raise ApiValueError(
|
||||
"Invalid host index. Must be 0 <= index < %s"
|
||||
% len(local_var_host)
|
||||
)
|
||||
local_var_host = local_var_hosts[_host_index]
|
||||
{{/servers.0}}
|
||||
local_var_params = locals()
|
||||
|
||||
all_params = [
|
||||
{{^servers}}
|
||||
'servers': None,
|
||||
{{/servers}}
|
||||
},
|
||||
params_map={
|
||||
'all': [
|
||||
{{#allParams}}
|
||||
'{{paramName}}'{{^-last}},{{/-last}}
|
||||
'{{paramName}}',
|
||||
{{/allParams}}
|
||||
]
|
||||
all_params.extend(
|
||||
[
|
||||
'async_req',
|
||||
'_return_http_data_only',
|
||||
'_preload_content',
|
||||
'_request_timeout',
|
||||
'_request_auth'
|
||||
]
|
||||
)
|
||||
|
||||
for key, val in six.iteritems(local_var_params['kwargs']):
|
||||
if key not in all_params{{#servers.0}} and key != "_host_index"{{/servers.0}}:
|
||||
raise ApiTypeError(
|
||||
"Got an unexpected keyword argument '%s'"
|
||||
" to method {{operationId}}" % key
|
||||
)
|
||||
local_var_params[key] = val
|
||||
del local_var_params['kwargs']
|
||||
],
|
||||
{{#requiredParams}}
|
||||
{{#-first}}
|
||||
'required': [
|
||||
{{/-first}}
|
||||
'{{paramName}}',
|
||||
{{#-last}}
|
||||
],
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{^requiredParams}}
|
||||
'required': [],
|
||||
{{/requiredParams}}
|
||||
'nullable': [
|
||||
{{#allParams}}
|
||||
{{^isNullable}}
|
||||
{{#required}}
|
||||
# verify the required parameter '{{paramName}}' is set
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' not in local_var_params or # noqa: E501
|
||||
local_var_params['{{paramName}}'] is None): # noqa: E501
|
||||
raise ApiValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") # noqa: E501
|
||||
{{/required}}
|
||||
{{#isNullable}}
|
||||
'{{paramName}}',
|
||||
{{/isNullable}}
|
||||
{{/allParams}}
|
||||
|
||||
],
|
||||
'enum': [
|
||||
{{#allParams}}
|
||||
{{#isEnum}}
|
||||
'{{paramName}}',
|
||||
{{/isEnum}}
|
||||
{{/allParams}}
|
||||
],
|
||||
'validation': [
|
||||
{{#allParams}}
|
||||
{{#hasValidation}}
|
||||
{{#maxLength}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) > {{maxLength}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501
|
||||
{{/maxLength}}
|
||||
{{#minLength}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) < {{minLength}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501
|
||||
{{/minLength}}
|
||||
{{#maximum}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501
|
||||
{{/maximum}}
|
||||
{{#minimum}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501
|
||||
{{/minimum}}
|
||||
{{#pattern}}
|
||||
if self.api_client.client_side_validation and '{{paramName}}' in local_var_params and not re.search(r'{{{vendorExtensions.x-regex}}}', local_var_params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{{pattern}}}`") # noqa: E501
|
||||
{{/pattern}}
|
||||
{{#maxItems}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) > {{maxItems}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501
|
||||
{{/maxItems}}
|
||||
{{#minItems}}
|
||||
if self.api_client.client_side_validation and ('{{paramName}}' in local_var_params and # noqa: E501
|
||||
len(local_var_params['{{paramName}}']) < {{minItems}}): # noqa: E501
|
||||
raise ApiValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501
|
||||
{{/minItems}}
|
||||
'{{paramName}}',
|
||||
{{/hasValidation}}
|
||||
{{#-last}}
|
||||
{{/-last}}
|
||||
{{/allParams}}
|
||||
collection_formats = {}
|
||||
|
||||
path_params = {}
|
||||
{{#pathParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
path_params['{{baseName}}'] = local_var_params['{{paramName}}']{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/pathParams}}
|
||||
|
||||
query_params = []
|
||||
{{#queryParams}}
|
||||
if '{{paramName}}' in local_var_params and local_var_params['{{paramName}}'] is not None: # noqa: E501
|
||||
query_params.append(('{{baseName}}', local_var_params['{{paramName}}'])){{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/queryParams}}
|
||||
|
||||
header_params = {}
|
||||
{{#headerParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
header_params['{{baseName}}'] = local_var_params['{{paramName}}']{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/headerParams}}
|
||||
|
||||
form_params = []
|
||||
local_var_files = {}
|
||||
{{#formParams}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
{{^isFile}}form_params.append(('{{baseName}}', local_var_params['{{paramName}}'])){{/isFile}}{{#isFile}}local_var_files['{{baseName}}'] = local_var_params['{{paramName}}']{{/isFile}}{{#isArray}} # noqa: E501
|
||||
collection_formats['{{baseName}}'] = '{{collectionFormat}}'{{/isArray}} # noqa: E501
|
||||
{{/formParams}}
|
||||
|
||||
body_params = None
|
||||
{{#bodyParam}}
|
||||
if '{{paramName}}' in local_var_params:
|
||||
body_params = local_var_params['{{paramName}}']
|
||||
{{/bodyParam}}
|
||||
{{#hasProduces}}
|
||||
# HTTP header `Accept`
|
||||
header_params['Accept'] = self.api_client.select_header_accept(
|
||||
[{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501
|
||||
|
||||
{{/hasProduces}}
|
||||
{{#hasConsumes}}
|
||||
# HTTP header `Content-Type`
|
||||
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
|
||||
[{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]) # noqa: E501
|
||||
|
||||
{{/hasConsumes}}
|
||||
# Authentication setting
|
||||
auth_settings = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501
|
||||
|
||||
{{#returnType}}
|
||||
{{#responses}}
|
||||
{{#-first}}
|
||||
response_types_map = {
|
||||
{{/-first}}
|
||||
{{^isWildcard}}
|
||||
{{code}}: {{#dataType}}"{{dataType}}"{{/dataType}}{{^dataType}}None{{/dataType}},
|
||||
{{/isWildcard}}
|
||||
{{#-last}}
|
||||
}
|
||||
{{/-last}}
|
||||
{{/responses}}
|
||||
{{/returnType}}
|
||||
{{^returnType}}
|
||||
response_types_map = {}
|
||||
{{/returnType}}
|
||||
|
||||
return self.api_client.call_api(
|
||||
'{{{path}}}', '{{httpMethod}}',
|
||||
path_params,
|
||||
query_params,
|
||||
header_params,
|
||||
body=body_params,
|
||||
post_params=form_params,
|
||||
files=local_var_files,
|
||||
response_types_map=response_types_map,
|
||||
auth_settings=auth_settings,
|
||||
async_req=local_var_params.get('async_req'),
|
||||
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
|
||||
_preload_content=local_var_params.get('_preload_content', True),
|
||||
_request_timeout=local_var_params.get('_request_timeout'),
|
||||
{{#servers.0}}
|
||||
_host=local_var_host,
|
||||
{{/servers.0}}
|
||||
collection_formats=collection_formats,
|
||||
_request_auth=local_var_params.get('_request_auth'))
|
||||
]
|
||||
},
|
||||
root_map={
|
||||
'validations': {
|
||||
{{#allParams}}
|
||||
{{#hasValidation}}
|
||||
('{{paramName}}',): {
|
||||
{{#maxLength}}
|
||||
'max_length': {{maxLength}},{{/maxLength}}{{#minLength}}
|
||||
'min_length': {{minLength}},{{/minLength}}{{#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': {
|
||||
'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}}
|
||||
{{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}}
|
||||
},{{/pattern}}
|
||||
},
|
||||
{{/hasValidation}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'allowed_values': {
|
||||
{{#allParams}}
|
||||
{{#isEnum}}
|
||||
('{{paramName}}',): {
|
||||
{{#isNullable}}
|
||||
'None': None,{{/isNullable}}{{#allowableValues}}{{#enumVars}}
|
||||
"{{name}}": {{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
|
||||
},
|
||||
{{/isEnum}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'openapi_types': {
|
||||
{{#allParams}}
|
||||
'{{paramName}}':
|
||||
({{{dataType}}},),
|
||||
{{/allParams}}
|
||||
},
|
||||
'attribute_map': {
|
||||
{{#allParams}}
|
||||
{{^isBodyParam}}
|
||||
'{{paramName}}': '{{baseName}}',
|
||||
{{/isBodyParam}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'location_map': {
|
||||
{{#allParams}}
|
||||
'{{paramName}}': '{{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isCookieParam}}cookie{{/isCookieParam}}{{#isBodyParam}}body{{/isBodyParam}}',
|
||||
{{/allParams}}
|
||||
},
|
||||
'collection_format_map': {
|
||||
{{#allParams}}
|
||||
{{#collectionFormat}}
|
||||
'{{paramName}}': '{{collectionFormat}}',
|
||||
{{/collectionFormat}}
|
||||
{{/allParams}}
|
||||
}
|
||||
},
|
||||
headers_map={
|
||||
{{#hasProduces}}
|
||||
'accept': [
|
||||
{{#produces}}
|
||||
'{{{mediaType}}}'{{^-last}},{{/-last}}
|
||||
{{/produces}}
|
||||
],
|
||||
{{/hasProduces}}
|
||||
{{^hasProduces}}
|
||||
'accept': [],
|
||||
{{/hasProduces}}
|
||||
{{#hasConsumes}}
|
||||
'content_type': [
|
||||
{{#consumes}}
|
||||
'{{{mediaType}}}'{{^-last}},{{/-last}}
|
||||
{{/consumes}}
|
||||
]
|
||||
{{/hasConsumes}}
|
||||
{{^hasConsumes}}
|
||||
'content_type': [],
|
||||
{{/hasConsumes}}
|
||||
},
|
||||
api_client=api_client,
|
||||
callable=__{{operationId}}
|
||||
)
|
||||
{{/operation}}
|
||||
{{/operations}}
|
||||
|
@ -1,28 +1,37 @@
|
||||
# coding: utf-8
|
||||
{{>partial_header}}
|
||||
from __future__ import absolute_import
|
||||
|
||||
import atexit
|
||||
import datetime
|
||||
from dateutil.parser import parse
|
||||
import json
|
||||
import atexit
|
||||
import mimetypes
|
||||
from multiprocessing.pool import ThreadPool
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import typing
|
||||
from urllib.parse import quote
|
||||
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
from six.moves.urllib.parse import quote
|
||||
{{#tornado}}
|
||||
import tornado.gen
|
||||
{{/tornado}}
|
||||
|
||||
from {{packageName}}.configuration import Configuration
|
||||
import {{modelPackage}}
|
||||
from {{packageName}} import rest
|
||||
from {{packageName}}.exceptions import ApiValueError, ApiException
|
||||
from {{packageName}}.configuration import Configuration
|
||||
from {{packageName}}.exceptions import ApiTypeError, ApiValueError, ApiException
|
||||
from {{packageName}}.model_utils import (
|
||||
ModelNormal,
|
||||
ModelSimple,
|
||||
ModelComposed,
|
||||
check_allowed_values,
|
||||
check_validations,
|
||||
date,
|
||||
datetime,
|
||||
deserialize_file,
|
||||
file_type,
|
||||
model_to_dict,
|
||||
none_type,
|
||||
validate_and_convert_types
|
||||
)
|
||||
|
||||
|
||||
class ApiClient(object):
|
||||
@ -47,23 +56,12 @@ class ApiClient(object):
|
||||
to the API. More threads means more concurrent API requests.
|
||||
"""
|
||||
|
||||
PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
|
||||
NATIVE_TYPES_MAPPING = {
|
||||
'int': int,
|
||||
'long': int if six.PY3 else long, # noqa: F821
|
||||
'float': float,
|
||||
'str': str,
|
||||
'bool': bool,
|
||||
'date': datetime.date,
|
||||
'datetime': datetime.datetime,
|
||||
'object': object,
|
||||
}
|
||||
_pool = None
|
||||
|
||||
def __init__(self, configuration=None, header_name=None, header_value=None,
|
||||
cookie=None, pool_threads=1):
|
||||
if configuration is None:
|
||||
configuration = Configuration.get_default_copy()
|
||||
configuration = Configuration()
|
||||
self.configuration = configuration
|
||||
self.pool_threads = pool_threads
|
||||
|
||||
@ -74,27 +72,14 @@ class ApiClient(object):
|
||||
self.cookie = cookie
|
||||
# Set default User-Agent.
|
||||
self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}'
|
||||
self.client_side_validation = configuration.client_side_validation
|
||||
|
||||
{{#asyncio}}
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc_value, traceback):
|
||||
await self.close()
|
||||
{{/asyncio}}
|
||||
{{^asyncio}}
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.close()
|
||||
{{/asyncio}}
|
||||
|
||||
{{#asyncio}}async {{/asyncio}}def close(self):
|
||||
{{#asyncio}}
|
||||
await self.rest_client.close()
|
||||
{{/asyncio}}
|
||||
def close(self):
|
||||
if self._pool:
|
||||
self._pool.close()
|
||||
self._pool.join()
|
||||
@ -128,12 +113,24 @@ class ApiClient(object):
|
||||
@tornado.gen.coroutine
|
||||
{{/tornado}}
|
||||
{{#asyncio}}async {{/asyncio}}def __call_api(
|
||||
self, resource_path, method, path_params=None,
|
||||
query_params=None, header_params=None, body=None, post_params=None,
|
||||
files=None, response_types_map=None, auth_settings=None,
|
||||
_return_http_data_only=None, collection_formats=None,
|
||||
_preload_content=True, _request_timeout=None, _host=None,
|
||||
_request_auth=None):
|
||||
self,
|
||||
resource_path: str,
|
||||
method: str,
|
||||
path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
body: typing.Optional[typing.Any] = None,
|
||||
post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
|
||||
response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
|
||||
auth_settings: typing.Optional[typing.List[str]] = None,
|
||||
_return_http_data_only: typing.Optional[bool] = None,
|
||||
collection_formats: typing.Optional[typing.Dict[str, str]] = None,
|
||||
_preload_content: bool = True,
|
||||
_request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
|
||||
_host: typing.Optional[str] = None,
|
||||
_check_type: typing.Optional[bool] = None
|
||||
):
|
||||
|
||||
config = self.configuration
|
||||
|
||||
@ -173,15 +170,14 @@ class ApiClient(object):
|
||||
collection_formats)
|
||||
post_params.extend(self.files_parameters(files))
|
||||
|
||||
# auth setting
|
||||
self.update_params_for_auth(
|
||||
header_params, query_params, auth_settings,
|
||||
request_auth=_request_auth)
|
||||
|
||||
# body
|
||||
if body:
|
||||
body = self.sanitize_for_serialization(body)
|
||||
|
||||
# auth setting
|
||||
self.update_params_for_auth(header_params, query_params,
|
||||
auth_settings, resource_path, method, body)
|
||||
|
||||
# request url
|
||||
if _host is None:
|
||||
url = self.configuration.host + resource_path
|
||||
@ -197,35 +193,38 @@ class ApiClient(object):
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout)
|
||||
except ApiException as e:
|
||||
e.body = e.body.decode('utf-8') if six.PY3 else e.body
|
||||
e.body = e.body.decode('utf-8')
|
||||
raise e
|
||||
|
||||
content_type = response_data.getheader('content-type')
|
||||
|
||||
self.last_response = response_data
|
||||
|
||||
return_data = response_data
|
||||
|
||||
if not _preload_content:
|
||||
{{^tornado}}
|
||||
return return_data
|
||||
return (return_data)
|
||||
{{/tornado}}
|
||||
{{#tornado}}
|
||||
raise tornado.gen.Return(return_data)
|
||||
{{/tornado}}
|
||||
|
||||
response_type = response_types_map.get(response_data.status, None)
|
||||
return return_data
|
||||
|
||||
if six.PY3 and response_type not in ["file", "bytes"]:
|
||||
if response_type not in ["file", "bytes"]:
|
||||
match = None
|
||||
content_type = response_data.getheader('content-type')
|
||||
if content_type is not None:
|
||||
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
|
||||
encoding = match.group(1) if match else "utf-8"
|
||||
response_data.data = response_data.data.decode(encoding)
|
||||
|
||||
# deserialize response data
|
||||
|
||||
if response_type:
|
||||
return_data = self.deserialize(response_data, response_type)
|
||||
return_data = self.deserialize(
|
||||
response_data,
|
||||
response_type,
|
||||
_check_type
|
||||
)
|
||||
else:
|
||||
return_data = None
|
||||
|
||||
@ -244,9 +243,9 @@ class ApiClient(object):
|
||||
response_data.getheaders()))
|
||||
{{/tornado}}
|
||||
|
||||
def sanitize_for_serialization(self, obj):
|
||||
@classmethod
|
||||
def sanitize_for_serialization(cls, obj):
|
||||
"""Builds a JSON POST object.
|
||||
|
||||
If obj is None, return None.
|
||||
If obj is str, int, long, float, bool, return directly.
|
||||
If obj is datetime.datetime, datetime.date
|
||||
@ -254,106 +253,90 @@ class ApiClient(object):
|
||||
If obj is list, sanitize each element in the list.
|
||||
If obj is dict, return the dict.
|
||||
If obj is OpenAPI model, return the properties dict.
|
||||
|
||||
:param obj: The data to serialize.
|
||||
:return: The serialized form of data.
|
||||
"""
|
||||
if obj is None:
|
||||
return None
|
||||
elif isinstance(obj, self.PRIMITIVE_TYPES):
|
||||
if isinstance(obj, (ModelNormal, ModelComposed)):
|
||||
return {
|
||||
key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()
|
||||
}
|
||||
elif isinstance(obj, (str, int, float, none_type, bool)):
|
||||
return obj
|
||||
elif isinstance(obj, list):
|
||||
return [self.sanitize_for_serialization(sub_obj)
|
||||
for sub_obj in obj]
|
||||
elif isinstance(obj, tuple):
|
||||
return tuple(self.sanitize_for_serialization(sub_obj)
|
||||
for sub_obj in obj)
|
||||
elif isinstance(obj, (datetime.datetime, datetime.date)):
|
||||
elif isinstance(obj, (datetime, date)):
|
||||
return obj.isoformat()
|
||||
|
||||
elif isinstance(obj, ModelSimple):
|
||||
return cls.sanitize_for_serialization(obj.value)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
return [cls.sanitize_for_serialization(item) for item in obj]
|
||||
if isinstance(obj, dict):
|
||||
obj_dict = obj
|
||||
else:
|
||||
# Convert model obj to dict except
|
||||
# attributes `openapi_types`, `attribute_map`
|
||||
# and attributes which value is not None.
|
||||
# Convert attribute name to json key in
|
||||
# model definition for request.
|
||||
obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
|
||||
for attr, _ in six.iteritems(obj.openapi_types)
|
||||
if getattr(obj, attr) is not None}
|
||||
return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
|
||||
raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__))
|
||||
|
||||
return {key: self.sanitize_for_serialization(val)
|
||||
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.
|
||||
|
||||
:param response: RESTResponse object to be deserialized.
|
||||
:param response_type: class literal for
|
||||
deserialized object, or string of class name.
|
||||
:param response_type: For the response, a tuple containing:
|
||||
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
|
||||
:type _check_type: bool
|
||||
|
||||
:return: deserialized object.
|
||||
"""
|
||||
# handle file downloading
|
||||
# save response body into a tmp file and return the instance
|
||||
if response_type == "file":
|
||||
return self.__deserialize_file(response)
|
||||
if response_type == (file_type,):
|
||||
content_disposition = response.getheader("Content-Disposition")
|
||||
return deserialize_file(response.data, self.configuration,
|
||||
content_disposition=content_disposition)
|
||||
|
||||
# fetch data from response object
|
||||
try:
|
||||
data = json.loads(response.data)
|
||||
received_data = json.loads(response.data)
|
||||
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
|
||||
deserialized_data = validate_and_convert_types(
|
||||
received_data,
|
||||
response_type,
|
||||
['received_data'],
|
||||
True,
|
||||
_check_type,
|
||||
configuration=self.configuration
|
||||
)
|
||||
return deserialized_data
|
||||
|
||||
def __deserialize(self, data, klass):
|
||||
"""Deserializes dict, list, str into an object.
|
||||
|
||||
:param data: dict, list or str.
|
||||
:param klass: class literal, or string of class name.
|
||||
|
||||
:return: object.
|
||||
"""
|
||||
if data is None:
|
||||
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_datetime(data)
|
||||
else:
|
||||
return self.__deserialize_model(data, klass)
|
||||
|
||||
def call_api(self, resource_path, method,
|
||||
path_params=None, query_params=None, header_params=None,
|
||||
body=None, post_params=None, files=None,
|
||||
response_types_map=None, auth_settings=None,
|
||||
async_req=None, _return_http_data_only=None,
|
||||
collection_formats=None,_preload_content=True,
|
||||
_request_timeout=None, _host=None, _request_auth=None):
|
||||
def call_api(
|
||||
self,
|
||||
resource_path: str,
|
||||
method: str,
|
||||
path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
body: typing.Optional[typing.Any] = None,
|
||||
post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
|
||||
response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
|
||||
auth_settings: typing.Optional[typing.List[str]] = None,
|
||||
async_req: typing.Optional[bool] = None,
|
||||
_return_http_data_only: typing.Optional[bool] = None,
|
||||
collection_formats: typing.Optional[typing.Dict[str, str]] = None,
|
||||
_preload_content: bool = True,
|
||||
_request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
|
||||
_host: typing.Optional[str] = None,
|
||||
_check_type: typing.Optional[bool] = None
|
||||
):
|
||||
"""Makes the HTTP request (synchronous) and returns deserialized data.
|
||||
|
||||
To make an async_req request, set the async_req parameter.
|
||||
@ -368,25 +351,38 @@ class ApiClient(object):
|
||||
:param post_params dict: Request post form parameters,
|
||||
for `application/x-www-form-urlencoded`, `multipart/form-data`.
|
||||
:param auth_settings list: Auth Settings names for the request.
|
||||
:param response: Response data type.
|
||||
:param files dict: key -> filename, value -> filepath,
|
||||
for `multipart/form-data`.
|
||||
:param response_type: For the response, a tuple containing:
|
||||
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 files: key -> field name, value -> a list of open file
|
||||
objects for `multipart/form-data`.
|
||||
:type files: dict
|
||||
:param async_req bool: execute request asynchronously
|
||||
:type async_req: bool, optional
|
||||
:param _return_http_data_only: response data without head status code
|
||||
and headers
|
||||
:type _return_http_data_only: bool, optional
|
||||
:param collection_formats: dict of collection formats for path, query,
|
||||
header, and post parameters.
|
||||
:type collection_formats: dict, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:param _request_auth: set to override the auth_settings for an a single
|
||||
request; this effectively ignores the authentication
|
||||
in the spec for a single request.
|
||||
:type _request_token: dict, optional
|
||||
:param _check_type: boolean describing if the data back from the server
|
||||
should have its type checked.
|
||||
:type _check_type: bool, optional
|
||||
:return:
|
||||
If async_req parameter is True,
|
||||
the request will be called asynchronously.
|
||||
@ -398,23 +394,23 @@ class ApiClient(object):
|
||||
return self.__call_api(resource_path, method,
|
||||
path_params, query_params, header_params,
|
||||
body, post_params, files,
|
||||
response_types_map, auth_settings,
|
||||
response_type, auth_settings,
|
||||
_return_http_data_only, collection_formats,
|
||||
_preload_content, _request_timeout, _host,
|
||||
_request_auth)
|
||||
_check_type)
|
||||
|
||||
return self.pool.apply_async(self.__call_api, (resource_path,
|
||||
method, path_params,
|
||||
query_params,
|
||||
header_params, body,
|
||||
post_params, files,
|
||||
response_types_map,
|
||||
response_type,
|
||||
auth_settings,
|
||||
_return_http_data_only,
|
||||
collection_formats,
|
||||
_preload_content,
|
||||
_request_timeout,
|
||||
_host, _request_auth))
|
||||
_host, _check_type))
|
||||
|
||||
def request(self, method, url, query_params=None, headers=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
@ -436,8 +432,10 @@ class ApiClient(object):
|
||||
return self.rest_client.OPTIONS(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout)
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "POST":
|
||||
return self.rest_client.POST(url,
|
||||
query_params=query_params,
|
||||
@ -485,7 +483,7 @@ class ApiClient(object):
|
||||
new_params = []
|
||||
if collection_formats is None:
|
||||
collection_formats = {}
|
||||
for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
|
||||
for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
|
||||
if k in collection_formats:
|
||||
collection_format = collection_formats[k]
|
||||
if collection_format == 'multi':
|
||||
@ -505,27 +503,37 @@ class ApiClient(object):
|
||||
new_params.append((k, v))
|
||||
return new_params
|
||||
|
||||
def files_parameters(self, files=None):
|
||||
def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
|
||||
"""Builds form parameters.
|
||||
|
||||
:param files: File parameters.
|
||||
:return: Form parameters with files.
|
||||
:param files: None or a dict with key=param_name and
|
||||
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:
|
||||
for k, v in six.iteritems(files):
|
||||
if not v:
|
||||
params = []
|
||||
for param_name, file_instances in files.items():
|
||||
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
|
||||
file_names = v if type(v) is list else [v]
|
||||
for n in file_names:
|
||||
with open(n, 'rb') as f:
|
||||
filename = os.path.basename(f.name)
|
||||
filedata = f.read()
|
||||
mimetype = (mimetypes.guess_type(filename)[0] or
|
||||
'application/octet-stream')
|
||||
params.append(
|
||||
tuple([k, tuple([filename, filedata, mimetype])]))
|
||||
if file_instance.closed is True:
|
||||
raise ApiValueError(
|
||||
"Cannot read a closed file. The passed in file_type "
|
||||
"for %s must be open." % param_name
|
||||
)
|
||||
filename = os.path.basename(file_instance.name)
|
||||
filedata = file_instance.read()
|
||||
mimetype = (mimetypes.guess_type(filename)[0] or
|
||||
'application/octet-stream')
|
||||
params.append(
|
||||
tuple([param_name, tuple([filename, filedata, mimetype])]))
|
||||
file_instance.close()
|
||||
|
||||
return params
|
||||
|
||||
@ -562,156 +570,270 @@ class ApiClient(object):
|
||||
return content_types[0]
|
||||
|
||||
def update_params_for_auth(self, headers, querys, auth_settings,
|
||||
request_auth=None):
|
||||
resource_path, method, body):
|
||||
"""Updates header and query params based on authentication setting.
|
||||
|
||||
:param headers: Header parameters dict to be updated.
|
||||
:param querys: Query parameters tuple list to be updated.
|
||||
:param auth_settings: Authentication setting identifiers list.
|
||||
:param request_auth: if set, the provided settings will
|
||||
override the token in the configuration.
|
||||
:param resource_path: A string representation of the HTTP request resource path.
|
||||
:param method: A string representation of the HTTP request method.
|
||||
:param body: A object representing the body of the HTTP request.
|
||||
The object type is the return value of _encoder.default().
|
||||
"""
|
||||
if not auth_settings:
|
||||
return
|
||||
|
||||
if request_auth:
|
||||
self._apply_auth_params(headers, querys, request_auth)
|
||||
return
|
||||
|
||||
for auth in auth_settings:
|
||||
auth_setting = self.configuration.auth_settings().get(auth)
|
||||
if auth_setting:
|
||||
self._apply_auth_params(headers, querys, auth_setting)
|
||||
if auth_setting['in'] == 'cookie':
|
||||
headers['Cookie'] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'header':
|
||||
if auth_setting['type'] != 'http-signature':
|
||||
headers[auth_setting['key']] = auth_setting['value']
|
||||
{{#hasHttpSignatureMethods}}
|
||||
else:
|
||||
# The HTTP signature scheme requires multiple HTTP headers
|
||||
# that are calculated dynamically.
|
||||
signing_info = self.configuration.signing_info
|
||||
auth_headers = signing_info.get_http_signature_headers(
|
||||
resource_path, method, headers, body, querys)
|
||||
headers.update(auth_headers)
|
||||
{{/hasHttpSignatureMethods}}
|
||||
elif auth_setting['in'] == 'query':
|
||||
querys.append((auth_setting['key'], auth_setting['value']))
|
||||
else:
|
||||
raise ApiValueError(
|
||||
'Authentication token must be in `query` or `header`'
|
||||
)
|
||||
|
||||
def _apply_auth_params(self, headers, querys, auth_setting):
|
||||
"""Updates the request parameters based on a single auth_setting
|
||||
|
||||
:param headers: Header parameters dict to be updated.
|
||||
:param querys: Query parameters tuple list to be updated.
|
||||
:param auth_setting: auth settings for the endpoint
|
||||
class Endpoint(object):
|
||||
def __init__(self, settings=None, params_map=None, root_map=None,
|
||||
headers_map=None, api_client=None, callable=None):
|
||||
"""Creates an endpoint
|
||||
|
||||
Args:
|
||||
settings (dict): see below key value pairs
|
||||
'response_type' (tuple/None): response type
|
||||
'auth' (list): a list of auth type keys
|
||||
'endpoint_path' (str): the endpoint path
|
||||
'operation_id' (str): endpoint string identifier
|
||||
'http_method' (str): POST/PUT/PATCH/GET etc
|
||||
'servers' (list): list of str servers that this endpoint is at
|
||||
params_map (dict): see below key value pairs
|
||||
'all' (list): list of str endpoint parameter names
|
||||
'required' (list): list of required parameter names
|
||||
'nullable' (list): list of nullable parameter names
|
||||
'enum' (list): list of parameters with enum values
|
||||
'validation' (list): list of parameters with validations
|
||||
root_map
|
||||
'validations' (dict): the dict mapping endpoint parameter tuple
|
||||
paths to their validation dictionaries
|
||||
'allowed_values' (dict): the dict mapping endpoint parameter
|
||||
tuple paths to their allowed_values (enum) dictionaries
|
||||
'openapi_types' (dict): param_name to openapi type
|
||||
'attribute_map' (dict): param_name to camelCase name
|
||||
'location_map' (dict): param_name to 'body', 'file', 'form',
|
||||
'header', 'path', 'query'
|
||||
collection_format_map (dict): param_name to `csv` etc.
|
||||
headers_map (dict): see below key value pairs
|
||||
'accept' (list): list of Accept header strings
|
||||
'content_type' (list): list of Content-Type header strings
|
||||
api_client (ApiClient) api client instance
|
||||
callable (function): the function which is invoked when the
|
||||
Endpoint is called
|
||||
"""
|
||||
if auth_setting['in'] == 'cookie':
|
||||
headers['Cookie'] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'header':
|
||||
headers[auth_setting['key']] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'query':
|
||||
querys.append((auth_setting['key'], auth_setting['value']))
|
||||
else:
|
||||
raise ApiValueError(
|
||||
'Authentication token must be in `query` or `header`'
|
||||
)
|
||||
self.settings = settings
|
||||
self.params_map = params_map
|
||||
self.params_map['all'].extend([
|
||||
'async_req',
|
||||
'_host_index',
|
||||
'_preload_content',
|
||||
'_request_timeout',
|
||||
'_return_http_data_only',
|
||||
'_check_input_type',
|
||||
'_check_return_type'
|
||||
])
|
||||
self.params_map['nullable'].extend(['_request_timeout'])
|
||||
self.validations = root_map['validations']
|
||||
self.allowed_values = root_map['allowed_values']
|
||||
self.openapi_types = root_map['openapi_types']
|
||||
extra_types = {
|
||||
'async_req': (bool,),
|
||||
'_host_index': (none_type, 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.location_map = root_map['location_map']
|
||||
self.collection_format_map = root_map['collection_format_map']
|
||||
self.headers_map = headers_map
|
||||
self.api_client = api_client
|
||||
self.callable = callable
|
||||
|
||||
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
|
||||
|
||||
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:
|
||||
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_datetime(self, string):
|
||||
"""Deserializes string to datetime.
|
||||
|
||||
The string should be in iso8601 datetime format.
|
||||
|
||||
:param string: str.
|
||||
:return: datetime.
|
||||
"""
|
||||
try:
|
||||
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 __validate_inputs(self, kwargs):
|
||||
for param in self.params_map['enum']:
|
||||
if param in kwargs:
|
||||
check_allowed_values(
|
||||
self.allowed_values,
|
||||
(param,),
|
||||
kwargs[param]
|
||||
)
|
||||
|
||||
for param in self.params_map['validation']:
|
||||
if param in kwargs:
|
||||
check_validations(
|
||||
self.validations,
|
||||
(param,),
|
||||
kwargs[param],
|
||||
configuration=self.api_client.configuration
|
||||
)
|
||||
|
||||
if kwargs['_check_input_type'] is False:
|
||||
return
|
||||
|
||||
for key, value in kwargs.items():
|
||||
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 __deserialize_model(self, data, klass):
|
||||
"""Deserializes list or dict to model.
|
||||
def __gather_params(self, kwargs):
|
||||
params = {
|
||||
'body': None,
|
||||
'collection_format': {},
|
||||
'file': {},
|
||||
'form': [],
|
||||
'header': {},
|
||||
'path': {},
|
||||
'query': []
|
||||
}
|
||||
|
||||
:param data: dict, list.
|
||||
:param klass: class literal.
|
||||
:return: model object.
|
||||
for param_name, param_value in kwargs.items():
|
||||
param_location = self.location_map.get(param_name)
|
||||
if param_location is None:
|
||||
continue
|
||||
if param_location:
|
||||
if param_location == 'body':
|
||||
params['body'] = param_value
|
||||
continue
|
||||
base_name = self.attribute_map[param_name]
|
||||
if (param_location == 'form' and
|
||||
self.openapi_types[param_name] == (file_type,)):
|
||||
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'}:
|
||||
param_value_full = (base_name, param_value)
|
||||
params[param_location].append(param_value_full)
|
||||
if param_location not in {'form', 'query'}:
|
||||
params[param_location][base_name] = param_value
|
||||
collection_format = self.collection_format_map.get(param_name)
|
||||
if collection_format:
|
||||
params['collection_format'][base_name] = collection_format
|
||||
|
||||
return params
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
""" This method is invoked when endpoints are called
|
||||
Example:
|
||||
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
|
||||
api_instance = {{classname}}()
|
||||
api_instance.{{operationId}} # this is an instance of the class Endpoint
|
||||
api_instance.{{operationId}}() # this invokes api_instance.{{operationId}}.__call__()
|
||||
which then invokes the callable functions stored in that endpoint at
|
||||
api_instance.{{operationId}}.callable or self.callable in this class
|
||||
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
|
||||
"""
|
||||
has_discriminator = False
|
||||
if (hasattr(klass, 'get_real_child_model')
|
||||
and klass.discriminator_value_class_map):
|
||||
has_discriminator = True
|
||||
return self.callable(self, *args, **kwargs)
|
||||
|
||||
if not klass.openapi_types and has_discriminator is False:
|
||||
return data
|
||||
def call_with_http_info(self, **kwargs):
|
||||
|
||||
kwargs = {}
|
||||
if (data is not None and
|
||||
klass.openapi_types is not None and
|
||||
isinstance(data, (list, dict))):
|
||||
for attr, attr_type in six.iteritems(klass.openapi_types):
|
||||
if klass.attribute_map[attr] in data:
|
||||
value = data[klass.attribute_map[attr]]
|
||||
kwargs[attr] = self.__deserialize(value, attr_type)
|
||||
try:
|
||||
index = self.api_client.configuration.server_operation_index.get(
|
||||
self.settings['operation_id'], self.api_client.configuration.server_index
|
||||
) if kwargs['_host_index'] is None else kwargs['_host_index']
|
||||
server_variables = self.api_client.configuration.server_operation_variables.get(
|
||||
self.settings['operation_id'], self.api_client.configuration.server_variables
|
||||
)
|
||||
_host = self.api_client.configuration.get_host_from_settings(
|
||||
index, variables=server_variables, servers=self.settings['servers']
|
||||
)
|
||||
except IndexError:
|
||||
if self.settings['servers']:
|
||||
raise ApiValueError(
|
||||
"Invalid host index. Must be 0 <= index < %s" %
|
||||
len(self.settings['servers'])
|
||||
)
|
||||
_host = None
|
||||
|
||||
instance = klass(**kwargs)
|
||||
for key, value in kwargs.items():
|
||||
if key not in self.params_map['all']:
|
||||
raise ApiTypeError(
|
||||
"Got an unexpected parameter '%s'"
|
||||
" to method `%s`" %
|
||||
(key, self.settings['operation_id'])
|
||||
)
|
||||
# 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(
|
||||
"Value may not be None for non-nullable parameter `%s`"
|
||||
" when calling `%s`" %
|
||||
(key, self.settings['operation_id'])
|
||||
)
|
||||
|
||||
if has_discriminator:
|
||||
klass_name = instance.get_real_child_model(data)
|
||||
if klass_name:
|
||||
instance = self.__deserialize(data, klass_name)
|
||||
return instance
|
||||
for key in self.params_map['required']:
|
||||
if key not in kwargs.keys():
|
||||
raise ApiValueError(
|
||||
"Missing the required parameter `%s` when calling "
|
||||
"`%s`" % (key, self.settings['operation_id'])
|
||||
)
|
||||
|
||||
self.__validate_inputs(kwargs)
|
||||
|
||||
params = self.__gather_params(kwargs)
|
||||
|
||||
accept_headers_list = self.headers_map['accept']
|
||||
if accept_headers_list:
|
||||
params['header']['Accept'] = self.api_client.select_header_accept(
|
||||
accept_headers_list)
|
||||
|
||||
content_type_headers_list = self.headers_map['content_type']
|
||||
if content_type_headers_list:
|
||||
header_list = self.api_client.select_header_content_type(
|
||||
content_type_headers_list)
|
||||
params['header']['Content-Type'] = header_list
|
||||
|
||||
return self.api_client.call_api(
|
||||
self.settings['endpoint_path'], self.settings['http_method'],
|
||||
params['path'],
|
||||
params['query'],
|
||||
params['header'],
|
||||
body=params['body'],
|
||||
post_params=params['form'],
|
||||
files=params['file'],
|
||||
response_type=self.settings['response_type'],
|
||||
auth_settings=self.settings['auth'],
|
||||
async_req=kwargs['async_req'],
|
||||
_check_type=kwargs['_check_return_type'],
|
||||
_return_http_data_only=kwargs['_return_http_data_only'],
|
||||
_preload_content=kwargs['_preload_content'],
|
||||
_request_timeout=kwargs['_request_timeout'],
|
||||
_host=_host,
|
||||
collection_formats=params['collection_format'])
|
||||
|
@ -11,7 +11,7 @@ Method | HTTP request | Description
|
||||
{{#operations}}
|
||||
{{#operation}}
|
||||
# **{{{operationId}}}**
|
||||
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}={{{paramName}}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}})
|
||||
> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}{{^-last}}, {{/-last}}{{/defaultValue}}{{/requiredParams}})
|
||||
|
||||
{{{summary}}}{{#notes}}
|
||||
|
||||
@ -35,18 +35,17 @@ Method | HTTP request | Description
|
||||
{{#isOAuth}}
|
||||
* OAuth Authentication ({{name}}):
|
||||
{{/isOAuth }}
|
||||
{{> api_doc_example }}
|
||||
{{/authMethods}}
|
||||
{{/hasAuthMethods}}
|
||||
{{^hasAuthMethods}}
|
||||
{{> api_doc_example }}
|
||||
{{/hasAuthMethods}}
|
||||
### Parameters
|
||||
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
|
||||
Name | Type | Description | Notes
|
||||
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
|
||||
{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}
|
||||
{{/allParams}}
|
||||
{{#requiredParams}}{{^defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} |
|
||||
{{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | defaults to {{{.}}}
|
||||
{{/defaultValue}}{{/requiredParams}}{{#optionalParams}} **{{paramName}}** | {{^baseType}}**{{dataType}}**{{/baseType}}{{#baseType}}[**{{dataType}}**]({{baseType}}.md){{/baseType}}| {{description}} | [optional]{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}}
|
||||
{{/optionalParams}}
|
||||
|
||||
### Return type
|
||||
|
||||
|
@ -1,8 +1,10 @@
|
||||
```python
|
||||
from __future__ import print_function
|
||||
import time
|
||||
import {{{packageName}}}
|
||||
from {{{packageName}}}.rest import ApiException
|
||||
from {{apiPackage}} import {{classVarName}}
|
||||
{{#imports}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
from pprint import pprint
|
||||
{{> python_doc_auth_partial}}
|
||||
# Enter a context with an instance of the API client
|
||||
@ -13,14 +15,62 @@ with {{{packageName}}}.ApiClient(configuration) as api_client:
|
||||
with {{{packageName}}}.ApiClient() as api_client:
|
||||
{{/hasAuthMethods}}
|
||||
# Create an instance of the API class
|
||||
api_instance = {{{packageName}}}.{{{classname}}}(api_client)
|
||||
{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
|
||||
{{/allParams}}
|
||||
api_instance = {{classVarName}}.{{{classname}}}(api_client)
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#optionalParams}}
|
||||
{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}}
|
||||
{{/optionalParams}}
|
||||
{{#requiredParams}}
|
||||
{{#-last}}
|
||||
|
||||
# example passing only required values which don't have defaults set
|
||||
try:
|
||||
{{#summary}} # {{{.}}}
|
||||
{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}){{#returnType}}
|
||||
pprint(api_response){{/returnType}}
|
||||
except ApiException as e:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}{{^-last}}, {{/-last}}{{/defaultValue}}{{/requiredParams}})
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{#optionalParams}}
|
||||
{{#-last}}
|
||||
|
||||
# example passing only required values which don't have defaults set
|
||||
# and optional values
|
||||
try:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#optionalParams}}{{paramName}}={{paramName}}{{^-last}}, {{/-last}}{{/optionalParams}})
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/-last}}
|
||||
{{/optionalParams}}
|
||||
{{^requiredParams}}
|
||||
{{^optionalParams}}
|
||||
|
||||
# example, this endpoint has no required or optional parameters
|
||||
try:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}()
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/optionalParams}}
|
||||
{{/requiredParams}}
|
||||
```
|
||||
|
@ -2,20 +2,17 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import unittest
|
||||
|
||||
import {{packageName}}
|
||||
from {{apiPackage}}.{{classVarName}} import {{classname}} # noqa: E501
|
||||
from {{packageName}}.rest import ApiException
|
||||
|
||||
|
||||
class {{#operations}}Test{{classname}}(unittest.TestCase):
|
||||
"""{{classname}} unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
self.api = {{apiPackage}}.{{classVarName}}.{{classname}}() # noqa: E501
|
||||
self.api = {{classname}}() # noqa: E501
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
@ -2,8 +2,6 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import copy
|
||||
import logging
|
||||
{{^asyncio}}
|
||||
@ -12,8 +10,7 @@ import multiprocessing
|
||||
import sys
|
||||
import urllib3
|
||||
|
||||
import six
|
||||
from six.moves import http_client as httplib
|
||||
from http import client as http_client
|
||||
from {{packageName}}.exceptions import ApiValueError
|
||||
|
||||
|
||||
@ -302,9 +299,8 @@ conf = {{{packageName}}}.Configuration(
|
||||
# Enable client side validation
|
||||
self.client_side_validation = True
|
||||
|
||||
# Options to pass down to the underlying urllib3 socket
|
||||
self.socket_options = None
|
||||
"""Options to pass down to the underlying urllib3 socket
|
||||
"""
|
||||
|
||||
def __deepcopy__(self, memo):
|
||||
cls = self.__class__
|
||||
@ -389,7 +385,7 @@ conf = {{{packageName}}}.Configuration(
|
||||
# then add file handler and remove stream handler.
|
||||
self.logger_file_handler = logging.FileHandler(self.__logger_file)
|
||||
self.logger_file_handler.setFormatter(self.logger_formatter)
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
for _, logger in self.logger.items():
|
||||
logger.addHandler(self.logger_file_handler)
|
||||
|
||||
@property
|
||||
@ -411,17 +407,17 @@ conf = {{{packageName}}}.Configuration(
|
||||
self.__debug = value
|
||||
if self.__debug:
|
||||
# if debug status is True, turn on debug logging
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
for _, logger in self.logger.items():
|
||||
logger.setLevel(logging.DEBUG)
|
||||
# turn on httplib debug
|
||||
httplib.HTTPConnection.debuglevel = 1
|
||||
# turn on http_client debug
|
||||
http_client.HTTPConnection.debuglevel = 1
|
||||
else:
|
||||
# if debug status is False, turn off debug logging,
|
||||
# setting log level to default `logging.WARNING`
|
||||
for _, logger in six.iteritems(self.logger):
|
||||
for _, logger in self.logger.items():
|
||||
logger.setLevel(logging.WARNING)
|
||||
# turn off httplib debug
|
||||
httplib.HTTPConnection.debuglevel = 0
|
||||
# turn off http_client debug
|
||||
http_client.HTTPConnection.debuglevel = 0
|
||||
|
||||
@property
|
||||
def logger_format(self):
|
||||
|
@ -2,8 +2,6 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import six
|
||||
|
||||
|
||||
class OpenApiException(Exception):
|
||||
"""The base exception class for all OpenAPIExceptions"""
|
||||
@ -120,35 +118,11 @@ class ApiException(OpenApiException):
|
||||
return error_message
|
||||
|
||||
|
||||
class NotFoundException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(NotFoundException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class UnauthorizedException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(UnauthorizedException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class ForbiddenException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(ForbiddenException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
class ServiceException(ApiException):
|
||||
|
||||
def __init__(self, status=None, reason=None, http_resp=None):
|
||||
super(ServiceException, self).__init__(status, reason, http_resp)
|
||||
|
||||
|
||||
def render_path(path_to_item):
|
||||
"""Returns a string representation of a path"""
|
||||
result = ""
|
||||
for pth in path_to_item:
|
||||
if isinstance(pth, six.integer_types):
|
||||
if isinstance(pth, int):
|
||||
result += "[{0}]".format(pth)
|
||||
else:
|
||||
result += "['{0}']".format(pth)
|
||||
|
@ -3,7 +3,7 @@
|
||||
stages:
|
||||
- test
|
||||
|
||||
.nosetest:
|
||||
.tests:
|
||||
stage: test
|
||||
script:
|
||||
- pip install -r requirements.txt
|
||||
@ -15,24 +15,15 @@ stages:
|
||||
- pytest --cov={{{packageName}}}
|
||||
{{/useNose}}
|
||||
|
||||
nosetest-2.7:
|
||||
extends: .nosetest
|
||||
image: python:2.7-alpine
|
||||
nosetest-3.3:
|
||||
extends: .nosetest
|
||||
image: python:3.3-alpine
|
||||
nosetest-3.4:
|
||||
extends: .nosetest
|
||||
image: python:3.4-alpine
|
||||
nosetest-3.5:
|
||||
extends: .nosetest
|
||||
test-3.5:
|
||||
extends: .tests
|
||||
image: python:3.5-alpine
|
||||
nosetest-3.6:
|
||||
extends: .nosetest
|
||||
test-3.6:
|
||||
extends: .tests
|
||||
image: python:3.6-alpine
|
||||
nosetest-3.7:
|
||||
extends: .nosetest
|
||||
test-3.7:
|
||||
extends: .tests
|
||||
image: python:3.7-alpine
|
||||
nosetest-3.8:
|
||||
extends: .nosetest
|
||||
test-3.8:
|
||||
extends: .tests
|
||||
image: python:3.8-alpine
|
||||
|
@ -1,254 +1,59 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
{{> partial_header }}
|
||||
|
||||
import inspect
|
||||
import pprint
|
||||
import re # noqa: F401
|
||||
import six
|
||||
|
||||
from {{packageName}}.configuration import Configuration
|
||||
import sys # noqa: F401
|
||||
|
||||
import nulltype # noqa: F401
|
||||
|
||||
from {{packageName}}.model_utils import ( # noqa: F401
|
||||
ApiTypeError,
|
||||
ModelComposed,
|
||||
ModelNormal,
|
||||
ModelSimple,
|
||||
cached_property,
|
||||
change_keys_js_to_python,
|
||||
convert_js_args_to_python_args,
|
||||
date,
|
||||
datetime,
|
||||
file_type,
|
||||
none_type,
|
||||
validate_get_composed_info,
|
||||
)
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
class {{classname}}(object):
|
||||
"""NOTE: This class is auto generated by OpenAPI Generator.
|
||||
Ref: https://openapi-generator.tech
|
||||
{{#imports}}
|
||||
{{#-first}}
|
||||
|
||||
Do not edit the class manually.
|
||||
"""{{#allowableValues}}
|
||||
|
||||
"""
|
||||
allowed enum values
|
||||
"""
|
||||
{{#enumVars}}
|
||||
{{name}} = {{{value}}}{{^-last}}
|
||||
{{/-last}}
|
||||
{{/enumVars}}{{/allowableValues}}
|
||||
|
||||
{{#allowableValues}}
|
||||
allowable_values = [{{#enumVars}}{{name}}{{^-last}}, {{/-last}}{{/enumVars}}] # noqa: E501
|
||||
|
||||
{{/allowableValues}}
|
||||
"""
|
||||
Attributes:
|
||||
openapi_types (dict): The key is attribute name
|
||||
and the value is attribute type.
|
||||
attribute_map (dict): The key is attribute name
|
||||
and the value is json key in definition.
|
||||
"""
|
||||
openapi_types = {
|
||||
{{#vars}}
|
||||
'{{name}}': '{{{dataType}}}'{{^-last}},{{/-last}}
|
||||
{{/vars}}
|
||||
}
|
||||
|
||||
attribute_map = {
|
||||
{{#vars}}
|
||||
'{{name}}': '{{baseName}}'{{^-last}},{{/-last}}
|
||||
{{/vars}}
|
||||
}
|
||||
{{#discriminator}}
|
||||
|
||||
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}},{{/-last}}
|
||||
{{/children}}
|
||||
}
|
||||
{{/discriminator}}
|
||||
|
||||
def __init__(self{{#vars}}, {{name}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}, local_vars_configuration=None): # noqa: E501
|
||||
"""{{classname}} - a model defined in OpenAPI""" # noqa: E501
|
||||
if local_vars_configuration is None:
|
||||
local_vars_configuration = Configuration()
|
||||
self.local_vars_configuration = local_vars_configuration
|
||||
{{#vars}}{{#-first}}
|
||||
def lazy_import():
|
||||
{{/-first}}
|
||||
self._{{name}} = None
|
||||
{{/vars}}
|
||||
self.discriminator = {{#discriminator}}'{{{discriminatorName}}}'{{/discriminator}}{{^discriminator}}None{{/discriminator}}
|
||||
{{#vars}}{{#-first}}
|
||||
{{/-first}}
|
||||
{{#required}}
|
||||
self.{{name}} = {{name}}
|
||||
{{/required}}
|
||||
{{^required}}
|
||||
{{#isNullable}}
|
||||
self.{{name}} = {{name}}
|
||||
{{/isNullable}}
|
||||
{{^isNullable}}
|
||||
if {{name}} is not None:
|
||||
self.{{name}} = {{name}}
|
||||
{{/isNullable}}
|
||||
{{/required}}
|
||||
{{/vars}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
|
||||
{{#vars}}
|
||||
@property
|
||||
def {{name}}(self):
|
||||
"""Gets the {{name}} of this {{classname}}. # noqa: E501
|
||||
|
||||
{{#description}}
|
||||
{{{description}}} # noqa: E501
|
||||
{{/description}}
|
||||
|
||||
:return: The {{name}} of this {{classname}}. # noqa: E501
|
||||
:rtype: {{dataType}}
|
||||
"""
|
||||
return self._{{name}}
|
||||
|
||||
@{{name}}.setter
|
||||
def {{name}}(self, {{name}}):
|
||||
"""Sets the {{name}} of this {{classname}}.
|
||||
|
||||
{{#description}}
|
||||
{{{description}}} # noqa: E501
|
||||
{{/description}}
|
||||
|
||||
:param {{name}}: The {{name}} of this {{classname}}. # noqa: E501
|
||||
:type {{name}}: {{dataType}}
|
||||
"""
|
||||
{{^isNullable}}
|
||||
{{#required}}
|
||||
if self.local_vars_configuration.client_side_validation and {{name}} is None: # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must not be `None`") # noqa: E501
|
||||
{{/required}}
|
||||
{{/isNullable}}
|
||||
{{#isEnum}}
|
||||
{{#isContainer}}
|
||||
allowed_values = [{{#isNullable}}None,{{/isNullable}}{{#allowableValues}}{{#values}}{{#items.isString}}"{{/items.isString}}{{{this}}}{{#items.isString}}"{{/items.isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501
|
||||
{{^interfaces}}
|
||||
{{#isArray}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
not set({{{name}}}).issubset(set(allowed_values))): # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501
|
||||
.format(", ".join(map(str, set({{{name}}}) - set(allowed_values))), # noqa: E501
|
||||
", ".join(map(str, allowed_values)))
|
||||
)
|
||||
{{> model_templates/model_simple }}
|
||||
{{/isArray}}
|
||||
{{#isMap}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
not set({{{name}}}.keys()).issubset(set(allowed_values))): # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" # noqa: E501
|
||||
.format(", ".join(map(str, set({{{name}}}.keys()) - set(allowed_values))), # noqa: E501
|
||||
", ".join(map(str, allowed_values)))
|
||||
)
|
||||
{{/isMap}}
|
||||
{{/isContainer}}
|
||||
{{^isContainer}}
|
||||
allowed_values = [{{#isNullable}}None,{{/isNullable}}{{#allowableValues}}{{#values}}{{#isString}}"{{/isString}}{{{this}}}{{#isString}}"{{/isString}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] # noqa: E501
|
||||
if self.local_vars_configuration.client_side_validation and {{{name}}} not in allowed_values: # noqa: E501
|
||||
raise ValueError(
|
||||
"Invalid value for `{{{name}}}` ({0}), must be one of {1}" # noqa: E501
|
||||
.format({{{name}}}, allowed_values)
|
||||
)
|
||||
{{/isContainer}}
|
||||
{{#isEnum}}
|
||||
{{> model_templates/model_simple }}
|
||||
{{/isEnum}}
|
||||
{{#isAlias}}
|
||||
{{> model_templates/model_simple }}
|
||||
{{/isAlias}}
|
||||
{{^isArray}}
|
||||
{{^isEnum}}
|
||||
{{#hasValidation}}
|
||||
{{#maxLength}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) > {{maxLength}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") # noqa: E501
|
||||
{{/maxLength}}
|
||||
{{#minLength}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) < {{minLength}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") # noqa: E501
|
||||
{{/minLength}}
|
||||
{{#maximum}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}): # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") # noqa: E501
|
||||
{{/maximum}}
|
||||
{{#minimum}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}): # noqa: E501
|
||||
raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") # noqa: E501
|
||||
{{/minimum}}
|
||||
{{#pattern}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and not re.search(r'{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}})): # noqa: E501
|
||||
raise ValueError(r"Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") # noqa: E501
|
||||
{{/pattern}}
|
||||
{{#maxItems}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) > {{maxItems}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") # noqa: E501
|
||||
{{/maxItems}}
|
||||
{{#minItems}}
|
||||
if (self.local_vars_configuration.client_side_validation and
|
||||
{{name}} is not None and len({{name}}) < {{minItems}}):
|
||||
raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") # noqa: E501
|
||||
{{/minItems}}
|
||||
{{/hasValidation}}
|
||||
{{^isAlias}}
|
||||
{{> model_templates/model_normal }}
|
||||
{{/isAlias}}
|
||||
{{/isEnum}}
|
||||
|
||||
self._{{name}} = {{name}}
|
||||
|
||||
{{/vars}}
|
||||
{{#discriminator}}
|
||||
def get_real_child_model(self, data):
|
||||
"""Returns the real base class specified by the discriminator"""
|
||||
discriminator_key = self.attribute_map[self.discriminator]
|
||||
discriminator_value = data[discriminator_key]
|
||||
return self.discriminator_value_class_map.get(discriminator_value)
|
||||
|
||||
{{/discriminator}}
|
||||
def to_dict(self, serialize=False):
|
||||
"""Returns the model properties as a dict"""
|
||||
result = {}
|
||||
|
||||
def convert(x):
|
||||
if hasattr(x, "to_dict"):
|
||||
args = inspect.getargspec(x.to_dict).args
|
||||
if len(args) == 1:
|
||||
return x.to_dict()
|
||||
else:
|
||||
return x.to_dict(serialize)
|
||||
else:
|
||||
return x
|
||||
|
||||
for attr, _ in six.iteritems(self.openapi_types):
|
||||
value = getattr(self, attr)
|
||||
attr = self.attribute_map.get(attr, attr) if serialize else attr
|
||||
if isinstance(value, list):
|
||||
result[attr] = list(map(
|
||||
lambda x: convert(x),
|
||||
value
|
||||
))
|
||||
elif isinstance(value, dict):
|
||||
result[attr] = dict(map(
|
||||
lambda item: (item[0], convert(item[1])),
|
||||
value.items()
|
||||
))
|
||||
else:
|
||||
result[attr] = convert(value)
|
||||
|
||||
return result
|
||||
|
||||
def to_str(self):
|
||||
"""Returns the string representation of the model"""
|
||||
return pprint.pformat(self.to_dict())
|
||||
|
||||
def __repr__(self):
|
||||
"""For `print` and `pprint`"""
|
||||
return self.to_str()
|
||||
|
||||
def __eq__(self, other):
|
||||
"""Returns true if both objects are equal"""
|
||||
if not isinstance(other, {{classname}}):
|
||||
return False
|
||||
|
||||
return self.to_dict() == other.to_dict()
|
||||
|
||||
def __ne__(self, other):
|
||||
"""Returns true if both objects are not equal"""
|
||||
if not isinstance(other, {{classname}}):
|
||||
return True
|
||||
|
||||
return self.to_dict() != other.to_dict()
|
||||
{{/isArray}}
|
||||
{{/interfaces}}
|
||||
{{#interfaces}}
|
||||
{{#-last}}
|
||||
{{> model_templates/model_composed }}
|
||||
{{/-last}}
|
||||
{{/interfaces}}
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
@ -5,8 +5,31 @@
|
||||
## Properties
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}}
|
||||
{{/vars}}
|
||||
{{#isEnum}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}{{#allowableValues}}{{#defaultValue}}, {{/defaultValue}} must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}}
|
||||
{{/isEnum}}
|
||||
{{#isAlias}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}
|
||||
{{/isAlias}}
|
||||
{{#isArray}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}}{{#arrayModelType}}[**{{dataType}}**]({{arrayModelType}}.md){{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}
|
||||
{{/isArray}}
|
||||
{{#requiredVars}}
|
||||
{{^defaultValue}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredVars}}
|
||||
{{#requiredVars}}
|
||||
{{#defaultValue}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredVars}}
|
||||
{{#optionalVars}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}}
|
||||
{{/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)
|
||||
|
||||
|
@ -44,18 +44,18 @@
|
||||
validations = {
|
||||
{{#hasValidation}}
|
||||
('value',): {
|
||||
{{> python-experimental/model_templates/validations }}
|
||||
{{> model_templates/validations }}
|
||||
{{/hasValidation}}
|
||||
{{#requiredVars}}
|
||||
{{#hasValidation}}
|
||||
('{{name}}',): {
|
||||
{{> python-experimental/model_templates/validations }}
|
||||
{{> model_templates/validations }}
|
||||
{{/hasValidation}}
|
||||
{{/requiredVars}}
|
||||
{{#optionalVars}}
|
||||
{{#hasValidation}}
|
||||
('{{name}}',): {
|
||||
{{> python-experimental/model_templates/validations }}
|
||||
{{> model_templates/validations }}
|
||||
{{/hasValidation}}
|
||||
{{/optionalVars}}
|
||||
}
|
@ -10,7 +10,7 @@
|
||||
'_additional_properties_model_instances',
|
||||
])
|
||||
|
||||
{{> python-experimental/model_templates/method_init_shared }}
|
||||
{{> model_templates/method_init_shared }}
|
||||
|
||||
constant_args = {
|
||||
'_check_type': _check_type,
|
@ -7,7 +7,7 @@
|
||||
'_visited_composed_classes',
|
||||
])
|
||||
|
||||
{{> python-experimental/model_templates/method_init_shared }}
|
||||
{{> model_templates/method_init_shared }}
|
||||
|
||||
{{#isEnum}}
|
||||
self.value = value
|
@ -19,7 +19,7 @@
|
||||
{{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501
|
||||
{{/defaultValue}}
|
||||
{{/requiredVars}}
|
||||
{{> python-experimental/model_templates/docstring_init_required_kwargs }}
|
||||
{{> model_templates/docstring_init_required_kwargs }}
|
||||
{{#optionalVars}}
|
||||
{{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501
|
||||
{{/optionalVars}}
|
@ -18,7 +18,7 @@
|
||||
|
||||
Keyword Args:
|
||||
value ({{{dataType}}}):{{#description}} {{description}}.{{/description}}{{#defaultValue}} if omitted defaults to {{{defaultValue}}}{{/defaultValue}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501
|
||||
{{> python-experimental/model_templates/docstring_init_required_kwargs }}
|
||||
{{> model_templates/docstring_init_required_kwargs }}
|
||||
"""
|
||||
|
||||
if 'value' in kwargs:
|
@ -5,15 +5,15 @@ class {{classname}}(ModelComposed):
|
||||
Do not edit the class manually.
|
||||
|
||||
Attributes:
|
||||
{{> python-experimental/model_templates/docstring_allowed }}
|
||||
{{> model_templates/docstring_allowed }}
|
||||
attribute_map (dict): The key is attribute name
|
||||
and the value is json key in definition.
|
||||
discriminator_value_class_map (dict): A dict to go from the discriminator
|
||||
variable value to the discriminator class name.
|
||||
{{> python-experimental/model_templates/docstring_openapi_validations }}
|
||||
{{> model_templates/docstring_openapi_validations }}
|
||||
"""
|
||||
|
||||
{{> python-experimental/model_templates/classvars }}
|
||||
{{> model_templates/classvars }}
|
||||
|
||||
attribute_map = {
|
||||
{{#requiredVars}}
|
||||
@ -24,7 +24,7 @@ class {{classname}}(ModelComposed):
|
||||
{{/optionalVars}}
|
||||
}
|
||||
|
||||
{{> python-experimental/model_templates/method_init_composed }}
|
||||
{{> model_templates/method_init_composed }}
|
||||
|
||||
@cached_property
|
||||
def _composed_schemas():
|
@ -5,15 +5,15 @@ class {{classname}}(ModelNormal):
|
||||
Do not edit the class manually.
|
||||
|
||||
Attributes:
|
||||
{{> python-experimental/model_templates/docstring_allowed }}
|
||||
{{> model_templates/docstring_allowed }}
|
||||
attribute_map (dict): The key is attribute name
|
||||
and the value is json key in definition.
|
||||
discriminator_value_class_map (dict): A dict to go from the discriminator
|
||||
variable value to the discriminator class name.
|
||||
{{> python-experimental/model_templates/docstring_openapi_validations }}
|
||||
{{> model_templates/docstring_openapi_validations }}
|
||||
"""
|
||||
|
||||
{{> python-experimental/model_templates/classvars }}
|
||||
{{> model_templates/classvars }}
|
||||
|
||||
attribute_map = {
|
||||
{{#requiredVars}}
|
||||
@ -26,4 +26,4 @@ class {{classname}}(ModelNormal):
|
||||
|
||||
_composed_schemas = {}
|
||||
|
||||
{{> python-experimental/model_templates/method_init_normal}}
|
||||
{{> model_templates/method_init_normal}}
|
@ -5,14 +5,14 @@ class {{classname}}(ModelSimple):
|
||||
Do not edit the class manually.
|
||||
|
||||
Attributes:
|
||||
{{> python-experimental/model_templates/docstring_allowed }}
|
||||
{{> python-experimental/model_templates/docstring_openapi_validations }}
|
||||
{{> model_templates/docstring_allowed }}
|
||||
{{> model_templates/docstring_openapi_validations }}
|
||||
"""
|
||||
|
||||
{{> python-experimental/model_templates/classvars }}
|
||||
{{> model_templates/classvars }}
|
||||
|
||||
attribute_map = {}
|
||||
|
||||
_composed_schemas = None
|
||||
|
||||
{{> python-experimental/model_templates/method_init_simple}}
|
||||
{{> model_templates/method_init_simple}}
|
@ -2,16 +2,17 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
import datetime
|
||||
|
||||
import {{packageName}}
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
import {{packageName}}
|
||||
from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501
|
||||
from {{packageName}}.rest import ApiException
|
||||
{{#imports}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
from {{modelPackage}}.{{classFilename}} import {{classname}}
|
||||
|
||||
|
||||
class Test{{classname}}(unittest.TestCase):
|
||||
"""{{classname}} unit test stubs"""
|
||||
@ -22,31 +23,11 @@ class Test{{classname}}(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def make_instance(self, include_optional):
|
||||
"""Test {{classname}}
|
||||
include_option is a boolean, when False only required
|
||||
params are included, when True both required and
|
||||
optional params are included """
|
||||
# model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501
|
||||
if include_optional :
|
||||
return {{classname}}(
|
||||
{{#vars}}
|
||||
{{name}} = {{#example}}{{{.}}}{{/example}}{{^example}}None{{/example}}{{^-last}}, {{/-last}}
|
||||
{{/vars}}
|
||||
)
|
||||
else :
|
||||
return {{classname}}(
|
||||
{{#vars}}
|
||||
{{#required}}
|
||||
{{name}} = {{#example}}{{{.}}}{{/example}}{{^example}}None{{/example}},
|
||||
{{/required}}
|
||||
{{/vars}}
|
||||
)
|
||||
|
||||
def test{{classname}}(self):
|
||||
"""Test {{classname}}"""
|
||||
inst_req_only = self.make_instance(include_optional=False)
|
||||
inst_req_and_optional = self.make_instance(include_optional=True)
|
||||
# FIXME: construct object with mandatory attributes with example values
|
||||
# model = {{classname}}() # noqa: E501
|
||||
pass
|
||||
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
@ -96,9 +96,9 @@ def composed_model_input_classes(cls):
|
||||
class OpenApiModel(object):
|
||||
"""The base class for all OpenAPIModels"""
|
||||
|
||||
{{> python-experimental/model_templates/method_set_attribute }}
|
||||
{{> model_templates/method_set_attribute }}
|
||||
|
||||
{{> python-experimental/model_templates/methods_shared }}
|
||||
{{> model_templates/methods_shared }}
|
||||
|
||||
def __new__(cls, *args, **kwargs):
|
||||
# this function uses the discriminator to
|
||||
@ -218,18 +218,18 @@ class ModelSimple(OpenApiModel):
|
||||
"""the parent class of models whose type != object in their
|
||||
swagger/openapi"""
|
||||
|
||||
{{> python-experimental/model_templates/methods_setattr_getattr_normal }}
|
||||
{{> model_templates/methods_setattr_getattr_normal }}
|
||||
|
||||
{{> python-experimental/model_templates/methods_tostr_eq_simple }}
|
||||
{{> model_templates/methods_tostr_eq_simple }}
|
||||
|
||||
|
||||
class ModelNormal(OpenApiModel):
|
||||
"""the parent class of models whose type == object in their
|
||||
swagger/openapi"""
|
||||
|
||||
{{> python-experimental/model_templates/methods_setattr_getattr_normal }}
|
||||
{{> model_templates/methods_setattr_getattr_normal }}
|
||||
|
||||
{{> python-experimental/model_templates/methods_todict_tostr_eq_shared}}
|
||||
{{> model_templates/methods_todict_tostr_eq_shared}}
|
||||
|
||||
|
||||
class ModelComposed(OpenApiModel):
|
||||
@ -258,9 +258,9 @@ class ModelComposed(OpenApiModel):
|
||||
which contain the value that the key is referring to.
|
||||
"""
|
||||
|
||||
{{> python-experimental/model_templates/methods_setattr_getattr_composed }}
|
||||
{{> model_templates/methods_setattr_getattr_composed }}
|
||||
|
||||
{{> python-experimental/model_templates/methods_todict_tostr_eq_shared}}
|
||||
{{> model_templates/methods_todict_tostr_eq_shared}}
|
||||
|
||||
|
||||
COERCION_INDEX_BY_TYPE = {
|
@ -1,9 +0,0 @@
|
||||
{{#apiInfo}}
|
||||
{{#apis}}
|
||||
{{#-first}}
|
||||
# do not import all apis into this module because that uses a lot of memory and stack frames
|
||||
# if you need the ability to import all apis from one package, import them with
|
||||
# from {{packageName}}.apis import {{classname}}
|
||||
{{/-first}}
|
||||
{{/apis}}
|
||||
{{/apiInfo}}
|
@ -1,5 +0,0 @@
|
||||
# we can not import model classes here because that would create a circular
|
||||
# reference which would not work in python2
|
||||
# do not import all models into this module because that uses a lot of memory and stack frames
|
||||
# if you need the ability to import all models from one package, import them with
|
||||
# from {{packageName}.models import ModelA, ModelB
|
@ -1,308 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import re # noqa: F401
|
||||
import sys # noqa: F401
|
||||
|
||||
from {{packageName}}.api_client import ApiClient, Endpoint
|
||||
from {{packageName}}.model_utils import ( # noqa: F401
|
||||
check_allowed_values,
|
||||
check_validations,
|
||||
date,
|
||||
datetime,
|
||||
file_type,
|
||||
none_type,
|
||||
validate_and_convert_types
|
||||
)
|
||||
{{#imports}}
|
||||
{{{import}}}
|
||||
{{/imports}}
|
||||
|
||||
|
||||
{{#operations}}
|
||||
class {{classname}}(object):
|
||||
"""NOTE: This class is auto generated by OpenAPI Generator
|
||||
Ref: https://openapi-generator.tech
|
||||
|
||||
Do not edit the class manually.
|
||||
"""
|
||||
|
||||
def __init__(self, api_client=None):
|
||||
if api_client is None:
|
||||
api_client = ApiClient()
|
||||
self.api_client = api_client
|
||||
{{#operation}}
|
||||
|
||||
def __{{operationId}}(
|
||||
self,
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}},
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{#defaultValue}}
|
||||
{{paramName}}={{{defaultValue}}},
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
**kwargs
|
||||
):
|
||||
"""{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501
|
||||
|
||||
{{#notes}}
|
||||
{{{notes}}} # noqa: E501
|
||||
{{/notes}}
|
||||
This method makes a synchronous HTTP request by default. To make an
|
||||
asynchronous HTTP request, please pass async_req=True
|
||||
|
||||
>>> thread = api.{{operationId}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}}{{paramName}}={{{defaultValue}}}, {{/defaultValue}}{{/requiredParams}}async_req=True)
|
||||
>>> result = thread.get()
|
||||
|
||||
{{#requiredParams}}
|
||||
{{#-last}}
|
||||
Args:
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}{{/description}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#requiredParams}}
|
||||
{{#defaultValue}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}]
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
|
||||
Keyword Args:{{#optionalParams}}
|
||||
{{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}}{{/optionalParams}}
|
||||
_return_http_data_only (bool): response data without head status
|
||||
code and headers. Default is True.
|
||||
_preload_content (bool): if False, the urllib3.HTTPResponse object
|
||||
will be returned without reading/decoding response data.
|
||||
Default is True.
|
||||
_request_timeout (float/tuple): timeout setting for this request. If one
|
||||
number provided, it will be total request timeout. It can also
|
||||
be a pair (tuple) of (connection, read) timeouts.
|
||||
Default is None.
|
||||
_check_input_type (bool): specifies if type checking
|
||||
should be done one the data sent to the server.
|
||||
Default is True.
|
||||
_check_return_type (bool): specifies if type checking
|
||||
should be done one the data received from the server.
|
||||
Default is True.
|
||||
_host_index (int/None): specifies the index of the server
|
||||
that we want to use.
|
||||
Default is read from the configuration.
|
||||
async_req (bool): execute request asynchronously
|
||||
|
||||
Returns:
|
||||
{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
||||
If the method is called asynchronously, returns the request
|
||||
thread.
|
||||
"""
|
||||
kwargs['async_req'] = kwargs.get(
|
||||
'async_req', False
|
||||
)
|
||||
kwargs['_return_http_data_only'] = kwargs.get(
|
||||
'_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')
|
||||
{{#requiredParams}}
|
||||
kwargs['{{paramName}}'] = \
|
||||
{{paramName}}
|
||||
{{/requiredParams}}
|
||||
return self.call_with_http_info(**kwargs)
|
||||
|
||||
self.{{operationId}} = Endpoint(
|
||||
settings={
|
||||
'response_type': {{#returnType}}({{{returnType}}},){{/returnType}}{{^returnType}}None{{/returnType}},
|
||||
{{#authMethods}}
|
||||
{{#-first}}
|
||||
'auth': [
|
||||
{{/-first}}
|
||||
'{{name}}'{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
],
|
||||
{{/-last}}
|
||||
{{/authMethods}}
|
||||
{{^authMethods}}
|
||||
'auth': [],
|
||||
{{/authMethods}}
|
||||
'endpoint_path': '{{{path}}}',
|
||||
'operation_id': '{{operationId}}',
|
||||
'http_method': '{{httpMethod}}',
|
||||
{{#servers}}
|
||||
{{#-first}}
|
||||
'servers': [
|
||||
{{/-first}}
|
||||
{
|
||||
'url': "{{{url}}}",
|
||||
'description': "{{{description}}}{{^description}}No description provided{{/description}}",
|
||||
{{#variables}}
|
||||
{{#-first}}
|
||||
'variables': {
|
||||
{{/-first}}
|
||||
'{{{name}}}': {
|
||||
'description': "{{{description}}}{{^description}}No description provided{{/description}}",
|
||||
'default_value': "{{{defaultValue}}}",
|
||||
{{#enumValues}}
|
||||
{{#-first}}
|
||||
'enum_values': [
|
||||
{{/-first}}
|
||||
"{{{.}}}"{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
]
|
||||
{{/-last}}
|
||||
{{/enumValues}}
|
||||
}{{^-last}},{{/-last}}
|
||||
{{#-last}}
|
||||
}
|
||||
{{/-last}}
|
||||
{{/variables}}
|
||||
},
|
||||
{{#-last}}
|
||||
]
|
||||
{{/-last}}
|
||||
{{/servers}}
|
||||
{{^servers}}
|
||||
'servers': None,
|
||||
{{/servers}}
|
||||
},
|
||||
params_map={
|
||||
'all': [
|
||||
{{#allParams}}
|
||||
'{{paramName}}',
|
||||
{{/allParams}}
|
||||
],
|
||||
{{#requiredParams}}
|
||||
{{#-first}}
|
||||
'required': [
|
||||
{{/-first}}
|
||||
'{{paramName}}',
|
||||
{{#-last}}
|
||||
],
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{^requiredParams}}
|
||||
'required': [],
|
||||
{{/requiredParams}}
|
||||
'nullable': [
|
||||
{{#allParams}}
|
||||
{{#isNullable}}
|
||||
'{{paramName}}',
|
||||
{{/isNullable}}
|
||||
{{/allParams}}
|
||||
],
|
||||
'enum': [
|
||||
{{#allParams}}
|
||||
{{#isEnum}}
|
||||
'{{paramName}}',
|
||||
{{/isEnum}}
|
||||
{{/allParams}}
|
||||
],
|
||||
'validation': [
|
||||
{{#allParams}}
|
||||
{{#hasValidation}}
|
||||
'{{paramName}}',
|
||||
{{/hasValidation}}
|
||||
{{/allParams}}
|
||||
]
|
||||
},
|
||||
root_map={
|
||||
'validations': {
|
||||
{{#allParams}}
|
||||
{{#hasValidation}}
|
||||
('{{paramName}}',): {
|
||||
{{#maxLength}}
|
||||
'max_length': {{maxLength}},{{/maxLength}}{{#minLength}}
|
||||
'min_length': {{minLength}},{{/minLength}}{{#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': {
|
||||
'pattern': r'{{{vendorExtensions.x-regex}}}', # noqa: E501{{#vendorExtensions.x-modifiers}}
|
||||
{{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}} re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}}
|
||||
},{{/pattern}}
|
||||
},
|
||||
{{/hasValidation}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'allowed_values': {
|
||||
{{#allParams}}
|
||||
{{#isEnum}}
|
||||
('{{paramName}}',): {
|
||||
{{#isNullable}}
|
||||
'None': None,{{/isNullable}}{{#allowableValues}}{{#enumVars}}
|
||||
"{{name}}": {{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
|
||||
},
|
||||
{{/isEnum}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'openapi_types': {
|
||||
{{#allParams}}
|
||||
'{{paramName}}':
|
||||
({{{dataType}}},),
|
||||
{{/allParams}}
|
||||
},
|
||||
'attribute_map': {
|
||||
{{#allParams}}
|
||||
{{^isBodyParam}}
|
||||
'{{paramName}}': '{{baseName}}',
|
||||
{{/isBodyParam}}
|
||||
{{/allParams}}
|
||||
},
|
||||
'location_map': {
|
||||
{{#allParams}}
|
||||
'{{paramName}}': '{{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isCookieParam}}cookie{{/isCookieParam}}{{#isBodyParam}}body{{/isBodyParam}}',
|
||||
{{/allParams}}
|
||||
},
|
||||
'collection_format_map': {
|
||||
{{#allParams}}
|
||||
{{#collectionFormat}}
|
||||
'{{paramName}}': '{{collectionFormat}}',
|
||||
{{/collectionFormat}}
|
||||
{{/allParams}}
|
||||
}
|
||||
},
|
||||
headers_map={
|
||||
{{#hasProduces}}
|
||||
'accept': [
|
||||
{{#produces}}
|
||||
'{{{mediaType}}}'{{^-last}},{{/-last}}
|
||||
{{/produces}}
|
||||
],
|
||||
{{/hasProduces}}
|
||||
{{^hasProduces}}
|
||||
'accept': [],
|
||||
{{/hasProduces}}
|
||||
{{#hasConsumes}}
|
||||
'content_type': [
|
||||
{{#consumes}}
|
||||
'{{{mediaType}}}'{{^-last}},{{/-last}}
|
||||
{{/consumes}}
|
||||
]
|
||||
{{/hasConsumes}}
|
||||
{{^hasConsumes}}
|
||||
'content_type': [],
|
||||
{{/hasConsumes}}
|
||||
},
|
||||
api_client=api_client,
|
||||
callable=__{{operationId}}
|
||||
)
|
||||
{{/operation}}
|
||||
{{/operations}}
|
@ -1,839 +0,0 @@
|
||||
# coding: utf-8
|
||||
{{>partial_header}}
|
||||
|
||||
import json
|
||||
import atexit
|
||||
import mimetypes
|
||||
from multiprocessing.pool import ThreadPool
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import typing
|
||||
from urllib.parse import quote
|
||||
|
||||
{{#tornado}}
|
||||
import tornado.gen
|
||||
{{/tornado}}
|
||||
|
||||
from {{packageName}} import rest
|
||||
from {{packageName}}.configuration import Configuration
|
||||
from {{packageName}}.exceptions import ApiTypeError, ApiValueError, ApiException
|
||||
from {{packageName}}.model_utils import (
|
||||
ModelNormal,
|
||||
ModelSimple,
|
||||
ModelComposed,
|
||||
check_allowed_values,
|
||||
check_validations,
|
||||
date,
|
||||
datetime,
|
||||
deserialize_file,
|
||||
file_type,
|
||||
model_to_dict,
|
||||
none_type,
|
||||
validate_and_convert_types
|
||||
)
|
||||
|
||||
|
||||
class ApiClient(object):
|
||||
"""Generic API client for OpenAPI client library builds.
|
||||
|
||||
OpenAPI generic API client. This client handles the client-
|
||||
server communication, and is invariant across implementations. Specifics of
|
||||
the methods and models for each application are generated from the OpenAPI
|
||||
templates.
|
||||
|
||||
NOTE: This class is auto generated by OpenAPI Generator.
|
||||
Ref: https://openapi-generator.tech
|
||||
Do not edit the class manually.
|
||||
|
||||
:param configuration: .Configuration object for this client
|
||||
:param header_name: a header to pass when making calls to the API.
|
||||
:param header_value: a header value to pass when making calls to
|
||||
the API.
|
||||
:param cookie: a cookie to include in the header when making calls
|
||||
to the API
|
||||
:param pool_threads: The number of threads to use for async requests
|
||||
to the API. More threads means more concurrent API requests.
|
||||
"""
|
||||
|
||||
_pool = None
|
||||
|
||||
def __init__(self, configuration=None, header_name=None, header_value=None,
|
||||
cookie=None, pool_threads=1):
|
||||
if configuration is None:
|
||||
configuration = Configuration()
|
||||
self.configuration = configuration
|
||||
self.pool_threads = pool_threads
|
||||
|
||||
self.rest_client = rest.RESTClientObject(configuration)
|
||||
self.default_headers = {}
|
||||
if header_name is not None:
|
||||
self.default_headers[header_name] = header_value
|
||||
self.cookie = cookie
|
||||
# Set default User-Agent.
|
||||
self.user_agent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/httpUserAgent}}'
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.close()
|
||||
|
||||
def close(self):
|
||||
if self._pool:
|
||||
self._pool.close()
|
||||
self._pool.join()
|
||||
self._pool = None
|
||||
if hasattr(atexit, 'unregister'):
|
||||
atexit.unregister(self.close)
|
||||
|
||||
@property
|
||||
def pool(self):
|
||||
"""Create thread pool on first request
|
||||
avoids instantiating unused threadpool for blocking clients.
|
||||
"""
|
||||
if self._pool is None:
|
||||
atexit.register(self.close)
|
||||
self._pool = ThreadPool(self.pool_threads)
|
||||
return self._pool
|
||||
|
||||
@property
|
||||
def user_agent(self):
|
||||
"""User agent for this API client"""
|
||||
return self.default_headers['User-Agent']
|
||||
|
||||
@user_agent.setter
|
||||
def user_agent(self, value):
|
||||
self.default_headers['User-Agent'] = value
|
||||
|
||||
def set_default_header(self, header_name, header_value):
|
||||
self.default_headers[header_name] = header_value
|
||||
|
||||
{{#tornado}}
|
||||
@tornado.gen.coroutine
|
||||
{{/tornado}}
|
||||
{{#asyncio}}async {{/asyncio}}def __call_api(
|
||||
self,
|
||||
resource_path: str,
|
||||
method: str,
|
||||
path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
body: typing.Optional[typing.Any] = None,
|
||||
post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
|
||||
response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
|
||||
auth_settings: typing.Optional[typing.List[str]] = None,
|
||||
_return_http_data_only: typing.Optional[bool] = None,
|
||||
collection_formats: typing.Optional[typing.Dict[str, str]] = None,
|
||||
_preload_content: bool = True,
|
||||
_request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
|
||||
_host: typing.Optional[str] = None,
|
||||
_check_type: typing.Optional[bool] = None
|
||||
):
|
||||
|
||||
config = self.configuration
|
||||
|
||||
# header parameters
|
||||
header_params = header_params or {}
|
||||
header_params.update(self.default_headers)
|
||||
if self.cookie:
|
||||
header_params['Cookie'] = self.cookie
|
||||
if header_params:
|
||||
header_params = self.sanitize_for_serialization(header_params)
|
||||
header_params = dict(self.parameters_to_tuples(header_params,
|
||||
collection_formats))
|
||||
|
||||
# path parameters
|
||||
if path_params:
|
||||
path_params = self.sanitize_for_serialization(path_params)
|
||||
path_params = self.parameters_to_tuples(path_params,
|
||||
collection_formats)
|
||||
for k, v in path_params:
|
||||
# specified safe chars, encode everything
|
||||
resource_path = resource_path.replace(
|
||||
'{%s}' % k,
|
||||
quote(str(v), safe=config.safe_chars_for_path_param)
|
||||
)
|
||||
|
||||
# query parameters
|
||||
if query_params:
|
||||
query_params = self.sanitize_for_serialization(query_params)
|
||||
query_params = self.parameters_to_tuples(query_params,
|
||||
collection_formats)
|
||||
|
||||
# post parameters
|
||||
if post_params or files:
|
||||
post_params = post_params if post_params else []
|
||||
post_params = self.sanitize_for_serialization(post_params)
|
||||
post_params = self.parameters_to_tuples(post_params,
|
||||
collection_formats)
|
||||
post_params.extend(self.files_parameters(files))
|
||||
|
||||
# body
|
||||
if body:
|
||||
body = self.sanitize_for_serialization(body)
|
||||
|
||||
# auth setting
|
||||
self.update_params_for_auth(header_params, query_params,
|
||||
auth_settings, resource_path, method, body)
|
||||
|
||||
# request url
|
||||
if _host is None:
|
||||
url = self.configuration.host + resource_path
|
||||
else:
|
||||
# use server/host defined in path or operation instead
|
||||
url = _host + resource_path
|
||||
|
||||
try:
|
||||
# perform request and return response
|
||||
response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request(
|
||||
method, url, query_params=query_params, headers=header_params,
|
||||
post_params=post_params, body=body,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout)
|
||||
except ApiException as e:
|
||||
e.body = e.body.decode('utf-8')
|
||||
raise e
|
||||
|
||||
content_type = response_data.getheader('content-type')
|
||||
|
||||
self.last_response = response_data
|
||||
|
||||
return_data = response_data
|
||||
|
||||
if not _preload_content:
|
||||
{{^tornado}}
|
||||
return (return_data)
|
||||
{{/tornado}}
|
||||
{{#tornado}}
|
||||
raise tornado.gen.Return(return_data)
|
||||
{{/tornado}}
|
||||
return return_data
|
||||
|
||||
if response_type not in ["file", "bytes"]:
|
||||
match = None
|
||||
if content_type is not None:
|
||||
match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
|
||||
encoding = match.group(1) if match else "utf-8"
|
||||
response_data.data = response_data.data.decode(encoding)
|
||||
|
||||
# deserialize response data
|
||||
if response_type:
|
||||
return_data = self.deserialize(
|
||||
response_data,
|
||||
response_type,
|
||||
_check_type
|
||||
)
|
||||
else:
|
||||
return_data = None
|
||||
|
||||
{{^tornado}}
|
||||
if _return_http_data_only:
|
||||
return (return_data)
|
||||
else:
|
||||
return (return_data, response_data.status,
|
||||
response_data.getheaders())
|
||||
{{/tornado}}
|
||||
{{#tornado}}
|
||||
if _return_http_data_only:
|
||||
raise tornado.gen.Return(return_data)
|
||||
else:
|
||||
raise tornado.gen.Return((return_data, response_data.status,
|
||||
response_data.getheaders()))
|
||||
{{/tornado}}
|
||||
|
||||
@classmethod
|
||||
def sanitize_for_serialization(cls, obj):
|
||||
"""Builds a JSON POST object.
|
||||
If obj is None, return None.
|
||||
If obj is str, int, long, float, bool, return directly.
|
||||
If obj is datetime.datetime, datetime.date
|
||||
convert to string in iso8601 format.
|
||||
If obj is list, sanitize each element in the list.
|
||||
If obj is dict, return the dict.
|
||||
If obj is OpenAPI model, return the properties dict.
|
||||
:param obj: The data to serialize.
|
||||
:return: The serialized form of data.
|
||||
"""
|
||||
if isinstance(obj, (ModelNormal, ModelComposed)):
|
||||
return {
|
||||
key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()
|
||||
}
|
||||
elif isinstance(obj, (str, int, float, none_type, bool)):
|
||||
return obj
|
||||
elif isinstance(obj, (datetime, date)):
|
||||
return obj.isoformat()
|
||||
elif isinstance(obj, ModelSimple):
|
||||
return cls.sanitize_for_serialization(obj.value)
|
||||
elif isinstance(obj, (list, tuple)):
|
||||
return [cls.sanitize_for_serialization(item) for item in obj]
|
||||
if isinstance(obj, dict):
|
||||
return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
|
||||
raise ApiValueError('Unable to prepare type {} for serialization'.format(obj.__class__.__name__))
|
||||
|
||||
def deserialize(self, response, response_type, _check_type):
|
||||
"""Deserializes response into an object.
|
||||
|
||||
:param response: RESTResponse object to be deserialized.
|
||||
:param response_type: For the response, a tuple containing:
|
||||
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
|
||||
:type _check_type: bool
|
||||
|
||||
:return: deserialized object.
|
||||
"""
|
||||
# handle file downloading
|
||||
# save response body into a tmp file and return the instance
|
||||
if response_type == (file_type,):
|
||||
content_disposition = response.getheader("Content-Disposition")
|
||||
return deserialize_file(response.data, self.configuration,
|
||||
content_disposition=content_disposition)
|
||||
|
||||
# fetch data from response object
|
||||
try:
|
||||
received_data = json.loads(response.data)
|
||||
except ValueError:
|
||||
received_data = response.data
|
||||
|
||||
# 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
|
||||
deserialized_data = validate_and_convert_types(
|
||||
received_data,
|
||||
response_type,
|
||||
['received_data'],
|
||||
True,
|
||||
_check_type,
|
||||
configuration=self.configuration
|
||||
)
|
||||
return deserialized_data
|
||||
|
||||
def call_api(
|
||||
self,
|
||||
resource_path: str,
|
||||
method: str,
|
||||
path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
|
||||
body: typing.Optional[typing.Any] = None,
|
||||
post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
|
||||
files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
|
||||
response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
|
||||
auth_settings: typing.Optional[typing.List[str]] = None,
|
||||
async_req: typing.Optional[bool] = None,
|
||||
_return_http_data_only: typing.Optional[bool] = None,
|
||||
collection_formats: typing.Optional[typing.Dict[str, str]] = None,
|
||||
_preload_content: bool = True,
|
||||
_request_timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
|
||||
_host: typing.Optional[str] = None,
|
||||
_check_type: typing.Optional[bool] = None
|
||||
):
|
||||
"""Makes the HTTP request (synchronous) and returns deserialized data.
|
||||
|
||||
To make an async_req request, set the async_req parameter.
|
||||
|
||||
:param resource_path: Path to method endpoint.
|
||||
:param method: Method to call.
|
||||
:param path_params: Path parameters in the url.
|
||||
:param query_params: Query parameters in the url.
|
||||
:param header_params: Header parameters to be
|
||||
placed in the request header.
|
||||
:param body: Request body.
|
||||
:param post_params dict: Request post form parameters,
|
||||
for `application/x-www-form-urlencoded`, `multipart/form-data`.
|
||||
:param auth_settings list: Auth Settings names for the request.
|
||||
:param response_type: For the response, a tuple containing:
|
||||
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 files: key -> field name, value -> a list of open file
|
||||
objects for `multipart/form-data`.
|
||||
:type files: dict
|
||||
:param async_req bool: execute request asynchronously
|
||||
:type async_req: bool, optional
|
||||
:param _return_http_data_only: response data without head status code
|
||||
and headers
|
||||
:type _return_http_data_only: bool, optional
|
||||
:param collection_formats: dict of collection formats for path, query,
|
||||
header, and post parameters.
|
||||
:type collection_formats: dict, optional
|
||||
:param _preload_content: if False, the urllib3.HTTPResponse object will
|
||||
be returned without reading/decoding response
|
||||
data. Default is True.
|
||||
:type _preload_content: bool, optional
|
||||
:param _request_timeout: timeout setting for this request. If one
|
||||
number provided, it will be total request
|
||||
timeout. It can also be a pair (tuple) of
|
||||
(connection, read) timeouts.
|
||||
:param _check_type: boolean describing if the data back from the server
|
||||
should have its type checked.
|
||||
:type _check_type: bool, optional
|
||||
:return:
|
||||
If async_req parameter is True,
|
||||
the request will be called asynchronously.
|
||||
The method will return the request thread.
|
||||
If parameter async_req is False or missing,
|
||||
then the method will return the response directly.
|
||||
"""
|
||||
if not async_req:
|
||||
return self.__call_api(resource_path, method,
|
||||
path_params, query_params, header_params,
|
||||
body, post_params, files,
|
||||
response_type, auth_settings,
|
||||
_return_http_data_only, collection_formats,
|
||||
_preload_content, _request_timeout, _host,
|
||||
_check_type)
|
||||
|
||||
return self.pool.apply_async(self.__call_api, (resource_path,
|
||||
method, path_params,
|
||||
query_params,
|
||||
header_params, body,
|
||||
post_params, files,
|
||||
response_type,
|
||||
auth_settings,
|
||||
_return_http_data_only,
|
||||
collection_formats,
|
||||
_preload_content,
|
||||
_request_timeout,
|
||||
_host, _check_type))
|
||||
|
||||
def request(self, method, url, query_params=None, headers=None,
|
||||
post_params=None, body=None, _preload_content=True,
|
||||
_request_timeout=None):
|
||||
"""Makes the HTTP request using RESTClient."""
|
||||
if method == "GET":
|
||||
return self.rest_client.GET(url,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
headers=headers)
|
||||
elif method == "HEAD":
|
||||
return self.rest_client.HEAD(url,
|
||||
query_params=query_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
headers=headers)
|
||||
elif method == "OPTIONS":
|
||||
return self.rest_client.OPTIONS(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "POST":
|
||||
return self.rest_client.POST(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "PUT":
|
||||
return self.rest_client.PUT(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "PATCH":
|
||||
return self.rest_client.PATCH(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
post_params=post_params,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
elif method == "DELETE":
|
||||
return self.rest_client.DELETE(url,
|
||||
query_params=query_params,
|
||||
headers=headers,
|
||||
_preload_content=_preload_content,
|
||||
_request_timeout=_request_timeout,
|
||||
body=body)
|
||||
else:
|
||||
raise ApiValueError(
|
||||
"http method must be `GET`, `HEAD`, `OPTIONS`,"
|
||||
" `POST`, `PATCH`, `PUT` or `DELETE`."
|
||||
)
|
||||
|
||||
def parameters_to_tuples(self, params, collection_formats):
|
||||
"""Get parameters as list of tuples, formatting collections.
|
||||
|
||||
:param params: Parameters as dict or list of two-tuples
|
||||
:param dict collection_formats: Parameter collection formats
|
||||
:return: Parameters as list of tuples, collections formatted
|
||||
"""
|
||||
new_params = []
|
||||
if collection_formats is None:
|
||||
collection_formats = {}
|
||||
for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
|
||||
if k in collection_formats:
|
||||
collection_format = collection_formats[k]
|
||||
if collection_format == 'multi':
|
||||
new_params.extend((k, value) for value in v)
|
||||
else:
|
||||
if collection_format == 'ssv':
|
||||
delimiter = ' '
|
||||
elif collection_format == 'tsv':
|
||||
delimiter = '\t'
|
||||
elif collection_format == 'pipes':
|
||||
delimiter = '|'
|
||||
else: # csv is the default
|
||||
delimiter = ','
|
||||
new_params.append(
|
||||
(k, delimiter.join(str(value) for value in v)))
|
||||
else:
|
||||
new_params.append((k, v))
|
||||
return new_params
|
||||
|
||||
def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
|
||||
"""Builds form parameters.
|
||||
|
||||
:param files: None or a dict with key=param_name and
|
||||
value is a list of open file objects
|
||||
:return: List of tuples of form parameters with file data
|
||||
"""
|
||||
if files is None:
|
||||
return []
|
||||
|
||||
params = []
|
||||
for param_name, file_instances in files.items():
|
||||
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
|
||||
if file_instance.closed is True:
|
||||
raise ApiValueError(
|
||||
"Cannot read a closed file. The passed in file_type "
|
||||
"for %s must be open." % param_name
|
||||
)
|
||||
filename = os.path.basename(file_instance.name)
|
||||
filedata = file_instance.read()
|
||||
mimetype = (mimetypes.guess_type(filename)[0] or
|
||||
'application/octet-stream')
|
||||
params.append(
|
||||
tuple([param_name, tuple([filename, filedata, mimetype])]))
|
||||
file_instance.close()
|
||||
|
||||
return params
|
||||
|
||||
def select_header_accept(self, accepts):
|
||||
"""Returns `Accept` based on an array of accepts provided.
|
||||
|
||||
:param accepts: List of headers.
|
||||
:return: Accept (e.g. application/json).
|
||||
"""
|
||||
if not accepts:
|
||||
return
|
||||
|
||||
accepts = [x.lower() for x in accepts]
|
||||
|
||||
if 'application/json' in accepts:
|
||||
return 'application/json'
|
||||
else:
|
||||
return ', '.join(accepts)
|
||||
|
||||
def select_header_content_type(self, content_types):
|
||||
"""Returns `Content-Type` based on an array of content_types provided.
|
||||
|
||||
:param content_types: List of content-types.
|
||||
:return: Content-Type (e.g. application/json).
|
||||
"""
|
||||
if not content_types:
|
||||
return 'application/json'
|
||||
|
||||
content_types = [x.lower() for x in content_types]
|
||||
|
||||
if 'application/json' in content_types or '*/*' in content_types:
|
||||
return 'application/json'
|
||||
else:
|
||||
return content_types[0]
|
||||
|
||||
def update_params_for_auth(self, headers, querys, auth_settings,
|
||||
resource_path, method, body):
|
||||
"""Updates header and query params based on authentication setting.
|
||||
|
||||
:param headers: Header parameters dict to be updated.
|
||||
:param querys: Query parameters tuple list to be updated.
|
||||
:param auth_settings: Authentication setting identifiers list.
|
||||
:param resource_path: A string representation of the HTTP request resource path.
|
||||
:param method: A string representation of the HTTP request method.
|
||||
:param body: A object representing the body of the HTTP request.
|
||||
The object type is the return value of _encoder.default().
|
||||
"""
|
||||
if not auth_settings:
|
||||
return
|
||||
|
||||
for auth in auth_settings:
|
||||
auth_setting = self.configuration.auth_settings().get(auth)
|
||||
if auth_setting:
|
||||
if auth_setting['in'] == 'cookie':
|
||||
headers['Cookie'] = auth_setting['value']
|
||||
elif auth_setting['in'] == 'header':
|
||||
if auth_setting['type'] != 'http-signature':
|
||||
headers[auth_setting['key']] = auth_setting['value']
|
||||
{{#hasHttpSignatureMethods}}
|
||||
else:
|
||||
# The HTTP signature scheme requires multiple HTTP headers
|
||||
# that are calculated dynamically.
|
||||
signing_info = self.configuration.signing_info
|
||||
auth_headers = signing_info.get_http_signature_headers(
|
||||
resource_path, method, headers, body, querys)
|
||||
headers.update(auth_headers)
|
||||
{{/hasHttpSignatureMethods}}
|
||||
elif auth_setting['in'] == 'query':
|
||||
querys.append((auth_setting['key'], auth_setting['value']))
|
||||
else:
|
||||
raise ApiValueError(
|
||||
'Authentication token must be in `query` or `header`'
|
||||
)
|
||||
|
||||
|
||||
class Endpoint(object):
|
||||
def __init__(self, settings=None, params_map=None, root_map=None,
|
||||
headers_map=None, api_client=None, callable=None):
|
||||
"""Creates an endpoint
|
||||
|
||||
Args:
|
||||
settings (dict): see below key value pairs
|
||||
'response_type' (tuple/None): response type
|
||||
'auth' (list): a list of auth type keys
|
||||
'endpoint_path' (str): the endpoint path
|
||||
'operation_id' (str): endpoint string identifier
|
||||
'http_method' (str): POST/PUT/PATCH/GET etc
|
||||
'servers' (list): list of str servers that this endpoint is at
|
||||
params_map (dict): see below key value pairs
|
||||
'all' (list): list of str endpoint parameter names
|
||||
'required' (list): list of required parameter names
|
||||
'nullable' (list): list of nullable parameter names
|
||||
'enum' (list): list of parameters with enum values
|
||||
'validation' (list): list of parameters with validations
|
||||
root_map
|
||||
'validations' (dict): the dict mapping endpoint parameter tuple
|
||||
paths to their validation dictionaries
|
||||
'allowed_values' (dict): the dict mapping endpoint parameter
|
||||
tuple paths to their allowed_values (enum) dictionaries
|
||||
'openapi_types' (dict): param_name to openapi type
|
||||
'attribute_map' (dict): param_name to camelCase name
|
||||
'location_map' (dict): param_name to 'body', 'file', 'form',
|
||||
'header', 'path', 'query'
|
||||
collection_format_map (dict): param_name to `csv` etc.
|
||||
headers_map (dict): see below key value pairs
|
||||
'accept' (list): list of Accept header strings
|
||||
'content_type' (list): list of Content-Type header strings
|
||||
api_client (ApiClient) api client instance
|
||||
callable (function): the function which is invoked when the
|
||||
Endpoint is called
|
||||
"""
|
||||
self.settings = settings
|
||||
self.params_map = params_map
|
||||
self.params_map['all'].extend([
|
||||
'async_req',
|
||||
'_host_index',
|
||||
'_preload_content',
|
||||
'_request_timeout',
|
||||
'_return_http_data_only',
|
||||
'_check_input_type',
|
||||
'_check_return_type'
|
||||
])
|
||||
self.params_map['nullable'].extend(['_request_timeout'])
|
||||
self.validations = root_map['validations']
|
||||
self.allowed_values = root_map['allowed_values']
|
||||
self.openapi_types = root_map['openapi_types']
|
||||
extra_types = {
|
||||
'async_req': (bool,),
|
||||
'_host_index': (none_type, 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.location_map = root_map['location_map']
|
||||
self.collection_format_map = root_map['collection_format_map']
|
||||
self.headers_map = headers_map
|
||||
self.api_client = api_client
|
||||
self.callable = callable
|
||||
|
||||
def __validate_inputs(self, kwargs):
|
||||
for param in self.params_map['enum']:
|
||||
if param in kwargs:
|
||||
check_allowed_values(
|
||||
self.allowed_values,
|
||||
(param,),
|
||||
kwargs[param]
|
||||
)
|
||||
|
||||
for param in self.params_map['validation']:
|
||||
if param in kwargs:
|
||||
check_validations(
|
||||
self.validations,
|
||||
(param,),
|
||||
kwargs[param],
|
||||
configuration=self.api_client.configuration
|
||||
)
|
||||
|
||||
if kwargs['_check_input_type'] is False:
|
||||
return
|
||||
|
||||
for key, value in kwargs.items():
|
||||
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):
|
||||
params = {
|
||||
'body': None,
|
||||
'collection_format': {},
|
||||
'file': {},
|
||||
'form': [],
|
||||
'header': {},
|
||||
'path': {},
|
||||
'query': []
|
||||
}
|
||||
|
||||
for param_name, param_value in kwargs.items():
|
||||
param_location = self.location_map.get(param_name)
|
||||
if param_location is None:
|
||||
continue
|
||||
if param_location:
|
||||
if param_location == 'body':
|
||||
params['body'] = param_value
|
||||
continue
|
||||
base_name = self.attribute_map[param_name]
|
||||
if (param_location == 'form' and
|
||||
self.openapi_types[param_name] == (file_type,)):
|
||||
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'}:
|
||||
param_value_full = (base_name, param_value)
|
||||
params[param_location].append(param_value_full)
|
||||
if param_location not in {'form', 'query'}:
|
||||
params[param_location][base_name] = param_value
|
||||
collection_format = self.collection_format_map.get(param_name)
|
||||
if collection_format:
|
||||
params['collection_format'][base_name] = collection_format
|
||||
|
||||
return params
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
""" This method is invoked when endpoints are called
|
||||
Example:
|
||||
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
|
||||
api_instance = {{classname}}()
|
||||
api_instance.{{operationId}} # this is an instance of the class Endpoint
|
||||
api_instance.{{operationId}}() # this invokes api_instance.{{operationId}}.__call__()
|
||||
which then invokes the callable functions stored in that endpoint at
|
||||
api_instance.{{operationId}}.callable or self.callable in this class
|
||||
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
|
||||
"""
|
||||
return self.callable(self, *args, **kwargs)
|
||||
|
||||
def call_with_http_info(self, **kwargs):
|
||||
|
||||
try:
|
||||
index = self.api_client.configuration.server_operation_index.get(
|
||||
self.settings['operation_id'], self.api_client.configuration.server_index
|
||||
) if kwargs['_host_index'] is None else kwargs['_host_index']
|
||||
server_variables = self.api_client.configuration.server_operation_variables.get(
|
||||
self.settings['operation_id'], self.api_client.configuration.server_variables
|
||||
)
|
||||
_host = self.api_client.configuration.get_host_from_settings(
|
||||
index, variables=server_variables, servers=self.settings['servers']
|
||||
)
|
||||
except IndexError:
|
||||
if self.settings['servers']:
|
||||
raise ApiValueError(
|
||||
"Invalid host index. Must be 0 <= index < %s" %
|
||||
len(self.settings['servers'])
|
||||
)
|
||||
_host = None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key not in self.params_map['all']:
|
||||
raise ApiTypeError(
|
||||
"Got an unexpected parameter '%s'"
|
||||
" to method `%s`" %
|
||||
(key, self.settings['operation_id'])
|
||||
)
|
||||
# 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(
|
||||
"Value may not be None for non-nullable parameter `%s`"
|
||||
" when calling `%s`" %
|
||||
(key, self.settings['operation_id'])
|
||||
)
|
||||
|
||||
for key in self.params_map['required']:
|
||||
if key not in kwargs.keys():
|
||||
raise ApiValueError(
|
||||
"Missing the required parameter `%s` when calling "
|
||||
"`%s`" % (key, self.settings['operation_id'])
|
||||
)
|
||||
|
||||
self.__validate_inputs(kwargs)
|
||||
|
||||
params = self.__gather_params(kwargs)
|
||||
|
||||
accept_headers_list = self.headers_map['accept']
|
||||
if accept_headers_list:
|
||||
params['header']['Accept'] = self.api_client.select_header_accept(
|
||||
accept_headers_list)
|
||||
|
||||
content_type_headers_list = self.headers_map['content_type']
|
||||
if content_type_headers_list:
|
||||
header_list = self.api_client.select_header_content_type(
|
||||
content_type_headers_list)
|
||||
params['header']['Content-Type'] = header_list
|
||||
|
||||
return self.api_client.call_api(
|
||||
self.settings['endpoint_path'], self.settings['http_method'],
|
||||
params['path'],
|
||||
params['query'],
|
||||
params['header'],
|
||||
body=params['body'],
|
||||
post_params=params['form'],
|
||||
files=params['file'],
|
||||
response_type=self.settings['response_type'],
|
||||
auth_settings=self.settings['auth'],
|
||||
async_req=kwargs['async_req'],
|
||||
_check_type=kwargs['_check_return_type'],
|
||||
_return_http_data_only=kwargs['_return_http_data_only'],
|
||||
_preload_content=kwargs['_preload_content'],
|
||||
_request_timeout=kwargs['_request_timeout'],
|
||||
_host=_host,
|
||||
collection_formats=params['collection_format'])
|
@ -1,76 +0,0 @@
|
||||
```python
|
||||
import time
|
||||
import {{{packageName}}}
|
||||
from {{apiPackage}} import {{classVarName}}
|
||||
{{#imports}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
from pprint import pprint
|
||||
{{> python_doc_auth_partial}}
|
||||
# Enter a context with an instance of the API client
|
||||
{{#hasAuthMethods}}
|
||||
with {{{packageName}}}.ApiClient(configuration) as api_client:
|
||||
{{/hasAuthMethods}}
|
||||
{{^hasAuthMethods}}
|
||||
with {{{packageName}}}.ApiClient() as api_client:
|
||||
{{/hasAuthMethods}}
|
||||
# Create an instance of the API class
|
||||
api_instance = {{classVarName}}.{{{classname}}}(api_client)
|
||||
{{#requiredParams}}
|
||||
{{^defaultValue}}
|
||||
{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredParams}}
|
||||
{{#optionalParams}}
|
||||
{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}}
|
||||
{{/optionalParams}}
|
||||
{{#requiredParams}}
|
||||
{{#-last}}
|
||||
|
||||
# example passing only required values which don't have defaults set
|
||||
try:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}{{^-last}}, {{/-last}}{{/defaultValue}}{{/requiredParams}})
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/-last}}
|
||||
{{/requiredParams}}
|
||||
{{#optionalParams}}
|
||||
{{#-last}}
|
||||
|
||||
# example passing only required values which don't have defaults set
|
||||
# and optional values
|
||||
try:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#optionalParams}}{{paramName}}={{paramName}}{{^-last}}, {{/-last}}{{/optionalParams}})
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/-last}}
|
||||
{{/optionalParams}}
|
||||
{{^requiredParams}}
|
||||
{{^optionalParams}}
|
||||
|
||||
# example, this endpoint has no required or optional parameters
|
||||
try:
|
||||
{{#summary}}
|
||||
# {{{.}}}
|
||||
{{/summary}}
|
||||
{{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}()
|
||||
{{#returnType}}
|
||||
pprint(api_response)
|
||||
{{/returnType}}
|
||||
except {{{packageName}}}.ApiException as e:
|
||||
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
|
||||
{{/optionalParams}}
|
||||
{{/requiredParams}}
|
||||
```
|
@ -1,59 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import re # noqa: F401
|
||||
import sys # noqa: F401
|
||||
|
||||
import nulltype # noqa: F401
|
||||
|
||||
from {{packageName}}.model_utils import ( # noqa: F401
|
||||
ApiTypeError,
|
||||
ModelComposed,
|
||||
ModelNormal,
|
||||
ModelSimple,
|
||||
cached_property,
|
||||
change_keys_js_to_python,
|
||||
convert_js_args_to_python_args,
|
||||
date,
|
||||
datetime,
|
||||
file_type,
|
||||
none_type,
|
||||
validate_get_composed_info,
|
||||
)
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
{{#imports}}
|
||||
{{#-first}}
|
||||
|
||||
def lazy_import():
|
||||
{{/-first}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
|
||||
|
||||
{{^interfaces}}
|
||||
{{#isArray}}
|
||||
{{> python-experimental/model_templates/model_simple }}
|
||||
{{/isArray}}
|
||||
{{#isEnum}}
|
||||
{{> python-experimental/model_templates/model_simple }}
|
||||
{{/isEnum}}
|
||||
{{#isAlias}}
|
||||
{{> python-experimental/model_templates/model_simple }}
|
||||
{{/isAlias}}
|
||||
{{^isArray}}
|
||||
{{^isEnum}}
|
||||
{{^isAlias}}
|
||||
{{> python-experimental/model_templates/model_normal }}
|
||||
{{/isAlias}}
|
||||
{{/isEnum}}
|
||||
{{/isArray}}
|
||||
{{/interfaces}}
|
||||
{{#interfaces}}
|
||||
{{#-last}}
|
||||
{{> python-experimental/model_templates/model_composed }}
|
||||
{{/-last}}
|
||||
{{/interfaces}}
|
||||
{{/model}}
|
||||
{{/models}}
|
@ -1,36 +0,0 @@
|
||||
{{#models}}{{#model}}# {{classname}}
|
||||
|
||||
{{#description}}{{&description}}
|
||||
{{/description}}
|
||||
## Properties
|
||||
Name | Type | Description | Notes
|
||||
------------ | ------------- | ------------- | -------------
|
||||
{{#isEnum}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}{{#allowableValues}}{{#defaultValue}}, {{/defaultValue}} must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}}
|
||||
{{/isEnum}}
|
||||
{{#isAlias}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}
|
||||
{{/isAlias}}
|
||||
{{#isArray}}
|
||||
**value** | {{^arrayModelType}}**{{dataType}}**{{/arrayModelType}}{{#arrayModelType}}[**{{dataType}}**]({{arrayModelType}}.md){{/arrayModelType}} | {{description}} | {{#defaultValue}}{{#hasRequired}} if omitted the server will use the default value of {{/hasRequired}}{{^hasRequired}}defaults to {{/hasRequired}}{{{.}}}{{/defaultValue}}
|
||||
{{/isArray}}
|
||||
{{#requiredVars}}
|
||||
{{^defaultValue}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{#isReadOnly}}[readonly] {{/isReadOnly}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredVars}}
|
||||
{{#requiredVars}}
|
||||
{{#defaultValue}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}defaults to {{{.}}}{{/defaultValue}}
|
||||
{{/defaultValue}}
|
||||
{{/requiredVars}}
|
||||
{{#optionalVars}}
|
||||
**{{name}}** | {{^complexType}}**{{dataType}}**{{/complexType}}{{#complexType}}[**{{dataType}}**]({{complexType}}.md){{/complexType}} | {{description}} | [optional] {{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}} if omitted the server will use the default value of {{{.}}}{{/defaultValue}}
|
||||
{{/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)
|
||||
|
||||
{{/model}}{{/models}}
|
@ -1,36 +0,0 @@
|
||||
# coding: utf-8
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import {{packageName}}
|
||||
{{#models}}
|
||||
{{#model}}
|
||||
{{#imports}}
|
||||
{{{.}}}
|
||||
{{/imports}}
|
||||
from {{modelPackage}}.{{classFilename}} import {{classname}}
|
||||
|
||||
|
||||
class Test{{classname}}(unittest.TestCase):
|
||||
"""{{classname}} unit test stubs"""
|
||||
|
||||
def setUp(self):
|
||||
pass
|
||||
|
||||
def tearDown(self):
|
||||
pass
|
||||
|
||||
def test{{classname}}(self):
|
||||
"""Test {{classname}}"""
|
||||
# FIXME: construct object with mandatory attributes with example values
|
||||
# model = {{classname}}() # noqa: E501
|
||||
pass
|
||||
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
@ -1,15 +0,0 @@
|
||||
{{#useNose}}
|
||||
coverage>=4.0.3
|
||||
nose>=1.3.7
|
||||
pluggy>=0.3.1
|
||||
py>=1.4.31
|
||||
randomize>=0.13
|
||||
{{/useNose}}
|
||||
{{^useNose}}
|
||||
pytest~=4.6.7 # needed for python 3.4
|
||||
pytest-cov>=2.8.1
|
||||
pytest-randomly==1.2.3 # needed for python 3.4
|
||||
{{/useNose}}
|
||||
{{#hasHttpSignatureMethods}}
|
||||
pycryptodome>=3.9.0
|
||||
{{/hasHttpSignatureMethods}}
|
@ -1,6 +1,5 @@
|
||||
nulltype
|
||||
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
|
||||
|
@ -2,21 +2,17 @@
|
||||
|
||||
{{>partial_header}}
|
||||
|
||||
from __future__ import absolute_import
|
||||
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import ssl
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import certifi
|
||||
# python 2 and python 3 compatibility library
|
||||
import six
|
||||
from six.moves.urllib.parse import urlencode
|
||||
import urllib3
|
||||
|
||||
from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError
|
||||
from {{packageName}}.exceptions import ApiException, ApiValueError
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -136,7 +132,7 @@ class RESTClientObject(object):
|
||||
|
||||
timeout = None
|
||||
if _request_timeout:
|
||||
if isinstance(_request_timeout, six.integer_types + (float, )): # noqa: E501,F821
|
||||
if isinstance(_request_timeout, (int, float)): # noqa: E501,F821
|
||||
timeout = urllib3.Timeout(total=_request_timeout)
|
||||
elif (isinstance(_request_timeout, tuple) and
|
||||
len(_request_timeout) == 2):
|
||||
@ -216,18 +212,6 @@ class RESTClientObject(object):
|
||||
logger.debug("response body: %s", r.data)
|
||||
|
||||
if not 200 <= r.status <= 299:
|
||||
if r.status == 401:
|
||||
raise UnauthorizedException(http_resp=r)
|
||||
|
||||
if r.status == 403:
|
||||
raise ForbiddenException(http_resp=r)
|
||||
|
||||
if r.status == 404:
|
||||
raise NotFoundException(http_resp=r)
|
||||
|
||||
if 500 <= r.status <= 599:
|
||||
raise ServiceException(http_resp=r)
|
||||
|
||||
raise ApiException(http_resp=r)
|
||||
|
||||
return r
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user