Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
81e594d
Dynamic server support
jirikuncar Jun 5, 2020
4985f27
regenerated
jirikuncar Jun 5, 2020
1fd2e65
Apply suggestions from code review
jirikuncar Jun 5, 2020
6caf66f
regenerated
jirikuncar Jun 5, 2020
5eec729
Add ParameterizedServer feature to Python experimental
jirikuncar Jun 5, 2020
df1c324
Fix lookup of server variables
jirikuncar Jun 5, 2020
3920645
Add tests and change default value for servers
jirikuncar Jun 8, 2020
7420edb
Fix server variables
jirikuncar Jun 8, 2020
5422cfd
Return base path when index is None
jirikuncar Jun 8, 2020
280837f
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 8, 2020
294d164
Use HOST
jirikuncar Jun 8, 2020
f38fc72
Apply suggestions from code review
jirikuncar Jun 11, 2020
8ec2cb7
Apply suggestions from code review
jirikuncar Jun 11, 2020
655ecd0
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 11, 2020
6e97360
regenerated
jirikuncar Jun 11, 2020
0a57b4c
Add specific tests for dynamic servers
jirikuncar Jun 12, 2020
5788068
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 12, 2020
1d19097
regenerated
jirikuncar Jun 12, 2020
ff976a4
add docstring
jirikuncar Jun 14, 2020
032533d
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 14, 2020
3706f4d
regenerated
jirikuncar Jun 15, 2020
3a1d0ca
Merge remote-tracking branch 'upstream/master' into python-experiment…
jirikuncar Jun 23, 2020
66df647
Fix wrong merge resolution
jirikuncar Jun 23, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
generatorName: python-experimental
outputDir: samples/openapi3/client/features/dynamic-servers/python-experimental/
inputSpec: modules/openapi-generator/src/test/resources/3_0/features/dynamic-servers.yaml
templateDir: modules/openapi-generator/src/main/resources/python
additionalProperties:
packageName: dynamic_servers
2 changes: 1 addition & 1 deletion docs/generators/python-experimental.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -162,7 +162,7 @@ sidebar_label: python-experimental
|Examples|✓|OAS2,OAS3
|XMLStructureDefinitions|✗|OAS2,OAS3
|MultiServer|✗|OAS3
|ParameterizedServer||OAS3
|ParameterizedServer||OAS3
|ParameterStyling|✗|OAS3
|Callbacks|✗|OAS3
|LinkObjects|✗|OAS3
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -72,6 +72,9 @@ public PythonClientExperimentalCodegen() {
SecurityFeature.ApiKey,
SecurityFeature.OAuth2_Implicit
))
.includeGlobalFeatures(
GlobalFeature.ParameterizedServer
)
.excludeGlobalFeatures(
GlobalFeature.XMLStructureDefinitions,
GlobalFeature.Callbacks,
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,6 +67,15 @@ class Configuration(object):
:param signing_info: Configuration parameters for the HTTP signature security scheme.
Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration
{{/hasHttpSignatureMethods}}
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

{{#hasAuthMethods}}
:Example:
Expand DownExpand Up@@ -155,20 +164,30 @@ conf = {{{packageName}}}.Configuration(

_default = None

def __init__(self, host="{{{basePath}}}",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
{{#hasHttpSignatureMethods}}
signing_info=None,
{{/hasHttpSignatureMethods}}
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
Comment thread
jirikuncar marked this conversation as resolved.
):
"""Constructor
"""
self.host = host
self._base_path = "{{{basePath}}}" if host is None else host
Comment thread
spacether marked this conversation as resolved.
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -565,14 +584,18 @@ conf = {{{packageName}}}.Configuration(
{{/servers}}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value

This comment was marked as resolved.

Comment thread
jirikuncar marked this conversation as resolved.
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -584,7 +607,7 @@ conf = {{{packageName}}}.Configuration(
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -599,3 +622,14 @@ conf = {{{packageName}}}.Configuration(
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,9 +99,9 @@ class {{classname}}(object):
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_host_index (int): specifies the index of the server
_host_index (int/None): specifies the index of the server
that we want to use.
Default is 0.
Default is read from the configuration.
Comment thread
spacether marked this conversation as resolved.
async_req (bool): execute request asynchronously

Returns:
Expand All@@ -127,7 +127,7 @@ class {{classname}}(object):
kwargs['_check_return_type'] = kwargs.get(
'_check_return_type', True
)
kwargs['_host_index'] = kwargs.get('_host_index', 0)
kwargs['_host_index'] = kwargs.get('_host_index')
{{#requiredParams}}
kwargs['{{paramName}}'] = \
{{paramName}}
Expand DownExpand Up@@ -156,13 +156,37 @@ class {{classname}}(object):
{{#-first}}
'servers': [
{{/-first}}
'{{{url}}}'{{^-last}},{{/-last}}
{
'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': [],
'servers': None,
{{/servers}}
},
params_map={
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -656,7 +656,7 @@ class Endpoint(object):
self.openapi_types = root_map['openapi_types']
extra_types = {
'async_req': (bool,),
'_host_index': (int,),
'_host_index': (none_type, int),
'_preload_content': (bool,),
'_request_timeout': (none_type, int, (int,), [int]),
'_return_http_data_only': (bool,),
Expand DownExpand Up@@ -755,7 +755,15 @@ class Endpoint(object):
def call_with_http_info(self, **kwargs):

try:
_host = self.settings['servers'][kwargs['_host_index']]
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(
Expand Down
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
openapi: 3.0.0
info:
description: This specification shows how to use dynamic servers.

@jirikuncarjirikuncarJun 12, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jimschubert I have tried to create a minimal specification on which we can showcase the dynamic server configuration to avoid modifications of default "Petstore" example. This should follow the work for extensions from #6469.

version: 1.0.0
title: OpenAPI Extension with dynamic servers
license:
name: Apache-2.0
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
tags:
- name: usage
description: Show usage of dynamic servers
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
variables:
server:
enum:
- 'petstore'
- 'qa-petstore'
- 'dev-petstore'
default: 'petstore'
port:
enum:
- '80'
- '8080'
default: '80'
- url: https://localhost:8080/{version}
description: The local server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v1'
paths:
/default:
get:
tags:
- usage
summary: Use default server
description: Use default server
operationId: defaultServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
/custom:
get:
tags:
- usage
servers:
- url: https://{server}.swagger.io:{port}/v2
variables:
server:
enum:
- 'custom-petstore'
- 'custom-qa-petstore'
- 'custom-dev-petstore'
default: 'custom-petstore'
port:
enum:
- '80'
- '8080'
default: '8080'
- url: https://localhost:8081/{version}
description: The local custom server
variables:
version:
enum:
- 'v1'
- 'v2'
- 'v3'
default: 'v2'
- url: https://third.example.com/{prefix}
description: The local custom server
variables:
prefix:
default: 'custom'
summary: Use custom server
description: Use custom server
operationId: customServer
responses:
'200':
description: successful operation
content:
application/json:
schema:
type: object
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,15 @@ class Configuration(object):
disabled. This can be useful to troubleshoot data validation problem, such as
when the OpenAPI document validation rules do not match the actual API data
received by the server.
:param server_index: Index to servers configuration.
:param server_variables: Mapping with string values to replace variables in
templated server configuration. The validation of enums is performed for
variables with defined enum values before.
:param server_operation_index: Mapping from operation ID to an index to server
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.

:Example:

Expand DownExpand Up@@ -109,17 +118,27 @@ class Configuration(object):

_default = None

def __init__(self, host="http://petstore.swagger.io:80/v2",
def __init__(self, host=None,
api_key=None, api_key_prefix=None,
username=None, password=None,
discard_unknown_keys=False,
disabled_client_side_validations="",
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
):
"""Constructor
"""
self.host = host
self._base_path = "http://petstore.swagger.io:80/v2" if host is None else host
"""Default Base url
"""
self.server_index = 0 if server_index is None and host is None else server_index
self.server_operation_index = server_operation_index or {}
"""Default server index
"""
self.server_variables = server_variables or {}
self.server_operation_variables = server_operation_variables or {}
"""Default server variables
"""
self.temp_folder_path = None
"""Temp file folder for downloading files
"""
Expand DownExpand Up@@ -437,14 +456,18 @@ def get_host_settings(self):
}
]

def get_host_from_settings(self, index, variables=None):
def get_host_from_settings(self, index, variables=None, servers=None):
"""Gets host URL based on the index and variables
:param index: array index of the host settings
:param variables: hash of variable and the corresponding value
:param servers: an array of host settings or None
:return: URL based on host settings
"""
if index is None:
return self._base_path

variables = {} if variables is None else variables
servers = self.get_host_settings()
servers = self.get_host_settings() if servers is None else servers

try:
server = servers[index]
Expand All@@ -456,7 +479,7 @@ def get_host_from_settings(self, index, variables=None):
url = server['url']

# go through variables and replace placeholders
for variable_name, variable in server['variables'].items():
for variable_name, variable in server.get('variables', {}).items():
used_value = variables.get(
variable_name, variable['default_value'])

Expand All@@ -471,3 +494,14 @@ def get_host_from_settings(self, index, variables=None):
url = url.replace("{" + variable_name + "}", used_value)

return url

@property
def host(self):
"""Return generated host."""
return self.get_host_from_settings(self.server_index, variables=self.server_variables)

@host.setter
def host(self, value):
"""Fix base path."""
self._base_path = value
self.server_index = None
Loading