github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/python/python-experimental/api.mustache (about)

     1  # coding: utf-8
     2  
     3  {{>partial_header}}
     4  
     5  from __future__ import absolute_import
     6  
     7  import re  # noqa: F401
     8  import sys  # noqa: F401
     9  
    10  # python 2 and python 3 compatibility library
    11  import six
    12  
    13  from {{packageName}}.api_client import ApiClient
    14  from {{packageName}}.exceptions import (
    15      ApiTypeError,
    16      ApiValueError
    17  )
    18  from {{packageName}}.model_utils import (  # noqa: F401
    19      check_allowed_values,
    20      check_validations,
    21      date,
    22      datetime,
    23      file_type,
    24      int,
    25      none_type,
    26      str,
    27      validate_and_convert_types
    28  )
    29  {{#imports}}
    30  {{{import}}}
    31  {{/imports}}
    32  
    33  
    34  {{#operations}}
    35  class {{classname}}(object):
    36      """NOTE: This class is auto generated by OpenAPI Generator
    37      Ref: https://openapi-generator.tech
    38  
    39      Do not edit the class manually.
    40      """
    41  
    42      def __init__(self, api_client=None):
    43          if api_client is None:
    44              api_client = ApiClient()
    45          self.api_client = api_client
    46  {{#operation}}
    47  
    48          def __{{operationId}}(
    49              self,
    50  {{#requiredParams}}
    51  {{^defaultValue}}
    52              {{paramName}},
    53  {{/defaultValue}}
    54  {{/requiredParams}}
    55  {{#requiredParams}}
    56  {{#defaultValue}}
    57              {{paramName}}={{{defaultValue}}},
    58  {{/defaultValue}}
    59  {{/requiredParams}}
    60              **kwargs
    61          ):
    62              """{{#summary}}{{{.}}}{{/summary}}{{^summary}}{{operationId}}{{/summary}}  # noqa: E501
    63  
    64  {{#notes}}
    65              {{{notes}}}  # noqa: E501
    66  {{/notes}}
    67              This method makes a synchronous HTTP request by default. To make an
    68              asynchronous HTTP request, please pass async_req=True
    69              >>> thread = api.{{operationId}}({{#requiredParams}}{{^defaultValue}}{{paramName}}, {{/defaultValue}}{{/requiredParams}}{{#requiredParams}}{{#defaultValue}}{{paramName}}={{{defaultValue}}}, {{/defaultValue}}{{/requiredParams}}async_req=True)
    70              >>> result = thread.get()
    71  
    72  {{#requiredParams}}
    73  {{#-last}}
    74              Args:
    75  {{/-last}}
    76  {{/requiredParams}}
    77  {{#requiredParams}}
    78  {{^defaultValue}}
    79                  {{paramName}} ({{dataType}}):{{#description}} {{description}}{{/description}}
    80  {{/defaultValue}}
    81  {{/requiredParams}}
    82  {{#requiredParams}}
    83  {{#defaultValue}}
    84                  {{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}]
    85  {{/defaultValue}}
    86  {{/requiredParams}}
    87  
    88              Keyword Args:{{#optionalParams}}
    89                  {{paramName}} ({{dataType}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}}{{/optionalParams}}
    90                  _return_http_data_only (bool): response data without head status
    91                      code and headers. Default is True.
    92                  _preload_content (bool): if False, the urllib3.HTTPResponse object
    93                      will be returned without reading/decoding response data.
    94                      Default is True.
    95                  _request_timeout (float/tuple): timeout setting for this request. If one
    96                      number provided, it will be total request timeout. It can also
    97                      be a pair (tuple) of (connection, read) timeouts.
    98                      Default is None.
    99                  _check_input_type (bool): specifies if type checking
   100                      should be done one the data sent to the server.
   101                      Default is True.
   102                  _check_return_type (bool): specifies if type checking
   103                      should be done one the data received from the server.
   104                      Default is True.
   105                  _host_index (int): specifies the index of the server
   106                      that we want to use.
   107                      Default is 0.
   108                  async_req (bool): execute request asynchronously
   109  
   110              Returns:
   111                  {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
   112                      If the method is called asynchronously, returns the request
   113                      thread.
   114              """
   115              kwargs['async_req'] = kwargs.get(
   116                  'async_req', False
   117              )
   118              kwargs['_return_http_data_only'] = kwargs.get(
   119                  '_return_http_data_only', True
   120              )
   121              kwargs['_preload_content'] = kwargs.get(
   122                  '_preload_content', True
   123              )
   124              kwargs['_request_timeout'] = kwargs.get(
   125                  '_request_timeout', None
   126              )
   127              kwargs['_check_input_type'] = kwargs.get(
   128                  '_check_input_type', True
   129              )
   130              kwargs['_check_return_type'] = kwargs.get(
   131                  '_check_return_type', True
   132              )
   133              kwargs['_host_index'] = kwargs.get('_host_index', 0)
   134  {{#requiredParams}}
   135              kwargs['{{paramName}}'] = \
   136                  {{paramName}}
   137  {{/requiredParams}}
   138              return self.call_with_http_info(**kwargs)
   139  
   140          self.{{operationId}} = Endpoint(
   141              settings={
   142                  'response_type': {{#returnType}}({{{returnType}}},){{/returnType}}{{^returnType}}None{{/returnType}},
   143  {{#authMethods}}
   144  {{#-first}}
   145                  'auth': [
   146  {{/-first}}
   147                      '{{name}}'{{^-last}},{{/-last}}
   148  {{#-last}}
   149                  ],
   150  {{/-last}}
   151  {{/authMethods}}
   152  {{^authMethods}}
   153                  'auth': [],
   154  {{/authMethods}}
   155                  'endpoint_path': '{{{path}}}',
   156                  'operation_id': '{{operationId}}',
   157                  'http_method': '{{httpMethod}}',
   158  {{#servers}}
   159  {{#-first}}
   160                  'servers': [
   161  {{/-first}}
   162                      '{{{url}}}'{{^-last}},{{/-last}}
   163  {{#-last}}
   164                  ]
   165  {{/-last}}
   166  {{/servers}}
   167  {{^servers}}
   168                  'servers': [],
   169  {{/servers}}
   170              },
   171              params_map={
   172                  'all': [
   173  {{#allParams}}
   174                      '{{paramName}}',
   175  {{/allParams}}
   176                  ],
   177  {{#requiredParams}}
   178  {{#-first}}
   179                  'required': [
   180  {{/-first}}
   181                      '{{paramName}}',
   182  {{#-last}}
   183                  ],
   184  {{/-last}}
   185  {{/requiredParams}}
   186  {{^requiredParams}}
   187                  'required': [],
   188  {{/requiredParams}}
   189                  'nullable': [
   190  {{#allParams}}
   191  {{#isNullable}}
   192                      '{{paramName}}',
   193  {{/isNullable}}
   194  {{/allParams}}
   195                  ],
   196                  'enum': [
   197  {{#allParams}}
   198  {{#isEnum}}
   199                      '{{paramName}}',
   200  {{/isEnum}}
   201  {{/allParams}}
   202                  ],
   203                  'validation': [
   204  {{#allParams}}
   205  {{#hasValidation}}
   206                      '{{paramName}}',
   207  {{/hasValidation}}
   208  {{/allParams}}
   209                  ]
   210              },
   211              root_map={
   212                  'validations': {
   213  {{#allParams}}
   214  {{#hasValidation}}
   215                      ('{{paramName}}',): {
   216  {{#maxLength}}
   217                          'max_length': {{maxLength}},{{/maxLength}}{{#minLength}}
   218                          'min_length': {{minLength}},{{/minLength}}{{#maxItems}}
   219                          'max_items': {{maxItems}},{{/maxItems}}{{#minItems}}
   220                          'min_items': {{minItems}},{{/minItems}}{{#maximum}}
   221                          {{#exclusiveMaximum}}'exclusive_maximum'{{/exclusiveMaximum}}'inclusive_maximum'{{^exclusiveMaximum}}{{/exclusiveMaximum}}: {{maximum}},{{/maximum}}{{#minimum}}
   222                          {{#exclusiveMinimum}}'exclusive_minimum'{{/exclusiveMinimum}}'inclusive_minimum'{{^exclusiveMinimum}}{{/exclusiveMinimum}}: {{minimum}},{{/minimum}}{{#pattern}}
   223                          'regex': {
   224                              'pattern': r'{{{vendorExtensions.x-regex}}}',  # noqa: E501{{#vendorExtensions.x-modifiers}}
   225                              {{#-first}}'flags': (re.{{.}}{{/-first}}{{^-first}}          re.{{.}}{{/-first}}{{^-last}} | {{/-last}}{{#-last}}){{/-last}}{{/vendorExtensions.x-modifiers}}
   226                          },{{/pattern}}
   227                      },
   228  {{/hasValidation}}
   229  {{/allParams}}
   230                  },
   231                  'allowed_values': {
   232  {{#allParams}}
   233  {{#isEnum}}
   234                      ('{{paramName}}',): {
   235  {{#isNullable}}
   236                          'None': None,{{/isNullable}}{{#allowableValues}}{{#enumVars}}
   237                          "{{name}}": {{{value}}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}}
   238                      },
   239  {{/isEnum}}
   240  {{/allParams}}
   241                  },
   242                  'openapi_types': {
   243  {{#allParams}}
   244                      '{{paramName}}':
   245                          ({{{dataType}}},),
   246  {{/allParams}}
   247                  },
   248                  'attribute_map': {
   249  {{#allParams}}
   250  {{^isBodyParam}}
   251                      '{{paramName}}': '{{baseName}}',
   252  {{/isBodyParam}}
   253  {{/allParams}}
   254                  },
   255                  'location_map': {
   256  {{#allParams}}
   257                      '{{paramName}}': '{{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isCookieParam}}cookie{{/isCookieParam}}{{#isBodyParam}}body{{/isBodyParam}}',
   258  {{/allParams}}
   259                  },
   260                  'collection_format_map': {
   261  {{#allParams}}
   262  {{#collectionFormat}}
   263                      '{{paramName}}': '{{collectionFormat}}',
   264  {{/collectionFormat}}
   265  {{/allParams}}
   266                  }
   267              },
   268              headers_map={
   269  {{#hasProduces}}
   270                  'accept': [
   271  {{#produces}}
   272                      '{{{mediaType}}}'{{^-last}},{{/-last}}
   273  {{/produces}}
   274                  ],
   275  {{/hasProduces}}
   276  {{^hasProduces}}
   277                  'accept': [],
   278  {{/hasProduces}}
   279  {{#hasConsumes}}
   280                  'content_type': [
   281  {{#consumes}}
   282                      '{{{mediaType}}}'{{^-last}},{{/-last}}
   283  {{/consumes}}
   284                  ]
   285  {{/hasConsumes}}
   286  {{^hasConsumes}}
   287                  'content_type': [],
   288  {{/hasConsumes}}
   289              },
   290              api_client=api_client,
   291              callable=__{{operationId}}
   292          )
   293  {{/operation}}
   294  {{/operations}}
   295  
   296  
   297  class Endpoint(object):
   298      def __init__(self, settings=None, params_map=None, root_map=None,
   299                   headers_map=None, api_client=None, callable=None):
   300          """Creates an endpoint
   301  
   302          Args:
   303              settings (dict): see below key value pairs
   304                  'response_type' (tuple/None): response type
   305                  'auth' (list): a list of auth type keys
   306                  'endpoint_path' (str): the endpoint path
   307                  'operation_id' (str): endpoint string identifier
   308                  'http_method' (str): POST/PUT/PATCH/GET etc
   309                  'servers' (list): list of str servers that this endpoint is at
   310              params_map (dict): see below key value pairs
   311                  'all' (list): list of str endpoint parameter names
   312                  'required' (list): list of required parameter names
   313                  'nullable' (list): list of nullable parameter names
   314                  'enum' (list): list of parameters with enum values
   315                  'validation' (list): list of parameters with validations
   316              root_map
   317                  'validations' (dict): the dict mapping endpoint parameter tuple
   318                      paths to their validation dictionaries
   319                  'allowed_values' (dict): the dict mapping endpoint parameter
   320                      tuple paths to their allowed_values (enum) dictionaries
   321                  'openapi_types' (dict): param_name to openapi type
   322                  'attribute_map' (dict): param_name to camelCase name
   323                  'location_map' (dict): param_name to  'body', 'file', 'form',
   324                      'header', 'path', 'query'
   325                  collection_format_map (dict): param_name to `csv` etc.
   326              headers_map (dict): see below key value pairs
   327                  'accept' (list): list of Accept header strings
   328                  'content_type' (list): list of Content-Type header strings
   329              api_client (ApiClient) api client instance
   330              callable (function): the function which is invoked when the
   331                  Endpoint is called
   332          """
   333          self.settings = settings
   334          self.params_map = params_map
   335          self.params_map['all'].extend([
   336              'async_req',
   337              '_host_index',
   338              '_preload_content',
   339              '_request_timeout',
   340              '_return_http_data_only',
   341              '_check_input_type',
   342              '_check_return_type'
   343          ])
   344          self.params_map['nullable'].extend(['_request_timeout'])
   345          self.validations = root_map['validations']
   346          self.allowed_values = root_map['allowed_values']
   347          self.openapi_types = root_map['openapi_types']
   348          extra_types = {
   349              'async_req': (bool,),
   350              '_host_index': (int,),
   351              '_preload_content': (bool,),
   352              '_request_timeout': (none_type, int, (int,), [int]),
   353              '_return_http_data_only': (bool,),
   354              '_check_input_type': (bool,),
   355              '_check_return_type': (bool,)
   356          }
   357          self.openapi_types.update(extra_types)
   358          self.attribute_map = root_map['attribute_map']
   359          self.location_map = root_map['location_map']
   360          self.collection_format_map = root_map['collection_format_map']
   361          self.headers_map = headers_map
   362          self.api_client = api_client
   363          self.callable = callable
   364  
   365      def __validate_inputs(self, kwargs):
   366          for param in self.params_map['enum']:
   367              if param in kwargs:
   368                  check_allowed_values(
   369                      self.allowed_values,
   370                      (param,),
   371                      kwargs[param]
   372                  )
   373  
   374          for param in self.params_map['validation']:
   375              if param in kwargs:
   376                  check_validations(
   377                      self.validations,
   378                      (param,),
   379                      kwargs[param]
   380                  )
   381  
   382          if kwargs['_check_input_type'] is False:
   383              return
   384  
   385          for key, value in six.iteritems(kwargs):
   386              fixed_val = validate_and_convert_types(
   387                  value,
   388                  self.openapi_types[key],
   389                  [key],
   390                  False,
   391                  kwargs['_check_input_type'],
   392                  configuration=self.api_client.configuration
   393              )
   394              kwargs[key] = fixed_val
   395  
   396      def __gather_params(self, kwargs):
   397          params = {
   398              'body': None,
   399              'collection_format': {},
   400              'file': {},
   401              'form': [],
   402              'header': {},
   403              'path': {},
   404              'query': []
   405          }
   406  
   407          for param_name, param_value in six.iteritems(kwargs):
   408              param_location = self.location_map.get(param_name)
   409              if param_location is None:
   410                  continue
   411              if param_location:
   412                  if param_location == 'body':
   413                      params['body'] = param_value
   414                      continue
   415                  base_name = self.attribute_map[param_name]
   416                  if (param_location == 'form' and
   417                          self.openapi_types[param_name] == (file_type,)):
   418                      params['file'][param_name] = [param_value]
   419                  elif (param_location == 'form' and
   420                          self.openapi_types[param_name] == ([file_type],)):
   421                      # param_value is already a list
   422                      params['file'][param_name] = param_value
   423                  elif param_location in {'form', 'query'}:
   424                      param_value_full = (base_name, param_value)
   425                      params[param_location].append(param_value_full)
   426                  if param_location not in {'form', 'query'}:
   427                      params[param_location][base_name] = param_value
   428                  collection_format = self.collection_format_map.get(param_name)
   429                  if collection_format:
   430                      params['collection_format'][base_name] = collection_format
   431  
   432          return params
   433  
   434      def __call__(self, *args, **kwargs):
   435          """ This method is invoked when endpoints are called
   436          Example:
   437          pet_api = PetApi()
   438          pet_api.add_pet  # this is an instance of the class Endpoint
   439          pet_api.add_pet()  # this invokes pet_api.add_pet.__call__()
   440          which then invokes the callable functions stored in that endpoint at
   441          pet_api.add_pet.callable or self.callable in this class
   442          """
   443          return self.callable(self, *args, **kwargs)
   444  
   445      def call_with_http_info(self, **kwargs):
   446  
   447          try:
   448              _host = self.settings['servers'][kwargs['_host_index']]
   449          except IndexError:
   450              if self.settings['servers']:
   451                  raise ApiValueError(
   452                      "Invalid host index. Must be 0 <= index < %s" %
   453                      len(self.settings['servers'])
   454                  )
   455              _host = None
   456  
   457          for key, value in six.iteritems(kwargs):
   458              if key not in self.params_map['all']:
   459                  raise ApiTypeError(
   460                      "Got an unexpected parameter '%s'"
   461                      " to method `%s`" %
   462                      (key, self.settings['operation_id'])
   463                  )
   464              # only throw this nullable ApiValueError if _check_input_type
   465              # is False, if _check_input_type==True we catch this case
   466              # in self.__validate_inputs
   467              if (key not in self.params_map['nullable'] and value is None
   468                      and kwargs['_check_input_type'] is False):
   469                  raise ApiValueError(
   470                      "Value may not be None for non-nullable parameter `%s`"
   471                      " when calling `%s`" %
   472                      (key, self.settings['operation_id'])
   473                  )
   474  
   475          for key in self.params_map['required']:
   476              if key not in kwargs.keys():
   477                  raise ApiValueError(
   478                      "Missing the required parameter `%s` when calling "
   479                      "`%s`" % (key, self.settings['operation_id'])
   480                  )
   481  
   482          self.__validate_inputs(kwargs)
   483  
   484          params = self.__gather_params(kwargs)
   485  
   486          accept_headers_list = self.headers_map['accept']
   487          if accept_headers_list:
   488              params['header']['Accept'] = self.api_client.select_header_accept(
   489                  accept_headers_list)
   490  
   491          content_type_headers_list = self.headers_map['content_type']
   492          if content_type_headers_list:
   493              header_list = self.api_client.select_header_content_type(
   494                  content_type_headers_list)
   495              params['header']['Content-Type'] = header_list
   496  
   497          return self.api_client.call_api(
   498              self.settings['endpoint_path'], self.settings['http_method'],
   499              params['path'],
   500              params['query'],
   501              params['header'],
   502              body=params['body'],
   503              post_params=params['form'],
   504              files=params['file'],
   505              response_type=self.settings['response_type'],
   506              auth_settings=self.settings['auth'],
   507              async_req=kwargs['async_req'],
   508              _check_type=kwargs['_check_return_type'],
   509              _return_http_data_only=kwargs['_return_http_data_only'],
   510              _preload_content=kwargs['_preload_content'],
   511              _request_timeout=kwargs['_request_timeout'],
   512              _host=_host,
   513              collection_formats=params['collection_format'])