cloudFPGA (cF) API  1.0
The documentation of the source code of cloudFPGA (cF)
api_client.py
Go to the documentation of this file.
1 # coding: utf-8
2 """
3  cloudFPGA Resource Manager API
4 
5  No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
6 
7  OpenAPI spec version: 0.8
8 
9  Generated by: https://github.com/swagger-api/swagger-codegen.git
10 """
11 from __future__ import absolute_import
12 
13 import datetime
14 import json
15 import mimetypes
16 from multiprocessing.pool import ThreadPool
17 import os
18 import re
19 import tempfile
20 
21 # python 2 and python 3 compatibility library
22 import six
23 from six.moves.urllib.parse import quote
24 
25 from swagger_client.configuration import Configuration
26 import swagger_client.models
27 from swagger_client import rest
28 
29 
30 class ApiClient(object):
31  """Generic API client for Swagger client library builds.
32 
33  Swagger generic API client. This client handles the client-
34  server communication, and is invariant across implementations. Specifics of
35  the methods and models for each application are generated from the Swagger
36  templates.
37 
38  NOTE: This class is auto generated by the swagger code generator program.
39  Ref: https://github.com/swagger-api/swagger-codegen
40  Do not edit the class manually.
41 
42  :param configuration: .Configuration object for this client
43  :param header_name: a header to pass when making calls to the API.
44  :param header_value: a header value to pass when making calls to
45  the API.
46  :param cookie: a cookie to include in the header when making calls
47  to the API
48  """
49 
50  PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types
51  NATIVE_TYPES_MAPPING = {
52  'int': int,
53  'long': int if six.PY3 else long, # noqa: F821
54  'float': float,
55  'str': str,
56  'bool': bool,
57  'date': datetime.date,
58  'datetime': datetime.datetime,
59  'object': object,
60  }
61 
62  def __init__(self, configuration=None, header_name=None, header_value=None,
63  cookie=None):
64  if configuration is None:
65  configuration = Configuration()
66  self.configurationconfiguration = configuration
67 
68  self.poolpool = ThreadPool()
69  self.rest_clientrest_client = rest.RESTClientObject(configuration)
70  self.default_headersdefault_headers = {}
71  if header_name is not None:
72  self.default_headersdefault_headers[header_name] = header_value
73  self.cookiecookie = cookie
74  # Set default User-Agent.
75  self.user_agentuser_agentuser_agentuser_agent = 'Swagger-Codegen/1.0.0/python'
76 
77  def __del__(self):
78  self.poolpool.close()
79  self.poolpool.join()
80 
81  @property
82  def user_agent(self):
83  """User agent for this API client"""
84  return self.default_headersdefault_headers['User-Agent']
85 
86  @user_agent.setter
87  def user_agent(self, value):
88  self.default_headersdefault_headers['User-Agent'] = value
89 
90  def set_default_header(self, header_name, header_value):
91  self.default_headersdefault_headers[header_name] = header_value
92 
93  def __call_api(
94  self, resource_path, method, path_params=None,
95  query_params=None, header_params=None, body=None, post_params=None,
96  files=None, response_type=None, auth_settings=None,
97  _return_http_data_only=None, collection_formats=None,
98  _preload_content=True, _request_timeout=None):
99 
100  config = self.configurationconfiguration
101 
102  # header parameters
103  header_params = header_params or {}
104  header_params.update(self.default_headersdefault_headers)
105  if self.cookiecookie:
106  header_params['Cookie'] = self.cookiecookie
107  if header_params:
108  header_params = self.sanitize_for_serializationsanitize_for_serialization(header_params)
109  header_params = dict(self.parameters_to_tuplesparameters_to_tuples(header_params,
110  collection_formats))
111 
112  # path parameters
113  if path_params:
114  path_params = self.sanitize_for_serializationsanitize_for_serialization(path_params)
115  path_params = self.parameters_to_tuplesparameters_to_tuples(path_params,
116  collection_formats)
117  for k, v in path_params:
118  # specified safe chars, encode everything
119  resource_path = resource_path.replace(
120  '{%s}' % k,
121  quote(str(v), safe=config.safe_chars_for_path_param)
122  )
123 
124  # query parameters
125  if query_params:
126  query_params = self.sanitize_for_serializationsanitize_for_serialization(query_params)
127  query_params = self.parameters_to_tuplesparameters_to_tuples(query_params,
128  collection_formats)
129 
130  # post parameters
131  if post_params or files:
132  post_params = self.prepare_post_parametersprepare_post_parameters(post_params, files)
133  post_params = self.sanitize_for_serializationsanitize_for_serialization(post_params)
134  post_params = self.parameters_to_tuplesparameters_to_tuples(post_params,
135  collection_formats)
136 
137  # auth setting
138  self.update_params_for_authupdate_params_for_auth(header_params, query_params, auth_settings)
139 
140  # body
141  if body:
142  body = self.sanitize_for_serializationsanitize_for_serialization(body)
143 
144  # request url
145  url = self.configurationconfiguration.host + resource_path
146 
147  # perform request and return response
148  response_data = self.requestrequest(
149  method, url, query_params=query_params, headers=header_params,
150  post_params=post_params, body=body,
151  _preload_content=_preload_content,
152  _request_timeout=_request_timeout)
153 
154  self.last_responselast_response = response_data
155 
156  return_data = response_data
157  if _preload_content:
158  # deserialize response data
159  if response_type:
160  return_data = self.deserializedeserialize(response_data, response_type)
161  else:
162  return_data = None
163 
164  if _return_http_data_only:
165  return (return_data)
166  else:
167  return (return_data, response_data.status,
168  response_data.getheaders())
169 
171  """Builds a JSON POST object.
172 
173  If obj is None, return None.
174  If obj is str, int, long, float, bool, return directly.
175  If obj is datetime.datetime, datetime.date
176  convert to string in iso8601 format.
177  If obj is list, sanitize each element in the list.
178  If obj is dict, return the dict.
179  If obj is swagger model, return the properties dict.
180 
181  :param obj: The data to serialize.
182  :return: The serialized form of data.
183  """
184  if obj is None:
185  return None
186  elif isinstance(obj, self.PRIMITIVE_TYPESPRIMITIVE_TYPES):
187  return obj
188  elif isinstance(obj, list):
189  return [self.sanitize_for_serializationsanitize_for_serialization(sub_obj)
190  for sub_obj in obj]
191  elif isinstance(obj, tuple):
192  return tuple(self.sanitize_for_serializationsanitize_for_serialization(sub_obj)
193  for sub_obj in obj)
194  elif isinstance(obj, (datetime.datetime, datetime.date)):
195  return obj.isoformat()
196 
197  if isinstance(obj, dict):
198  obj_dict = obj
199  else:
200  # Convert model obj to dict except
201  # attributes `swagger_types`, `attribute_map`
202  # and attributes which value is not None.
203  # Convert attribute name to json key in
204  # model definition for request.
205  obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
206  for attr, _ in six.iteritems(obj.swagger_types)
207  if getattr(obj, attr) is not None}
208 
209  return {key: self.sanitize_for_serializationsanitize_for_serialization(val)
210  for key, val in six.iteritems(obj_dict)}
211 
212  def deserialize(self, response, response_type):
213  """Deserializes response into an object.
214 
215  :param response: RESTResponse object to be deserialized.
216  :param response_type: class literal for
217  deserialized object, or string of class name.
218 
219  :return: deserialized object.
220  """
221  # handle file downloading
222  # save response body into a tmp file and return the instance
223  if response_type == "file":
224  return self.__deserialize_file__deserialize_file(response)
225 
226  # fetch data from response object
227  try:
228  data = json.loads(response.data)
229  except ValueError:
230  data = response.data
231 
232  return self.__deserialize__deserialize(data, response_type)
233 
234  def __deserialize(self, data, klass):
235  """Deserializes dict, list, str into an object.
236 
237  :param data: dict, list or str.
238  :param klass: class literal, or string of class name.
239 
240  :return: object.
241  """
242  if data is None:
243  return None
244 
245  if type(klass) == str:
246  if klass.startswith('list['):
247  sub_kls = re.match(r'list\[(.*)\]', klass).group(1)
248  return [self.__deserialize__deserialize(sub_data, sub_kls)
249  for sub_data in data]
250 
251  if klass.startswith('dict('):
252  sub_kls = re.match(r'dict\‍(([^,]*), (.*)\‍)', klass).group(2)
253  return {k: self.__deserialize__deserialize(v, sub_kls)
254  for k, v in six.iteritems(data)}
255 
256  # convert str to class
257  if klass in self.NATIVE_TYPES_MAPPINGNATIVE_TYPES_MAPPING:
258  klass = self.NATIVE_TYPES_MAPPINGNATIVE_TYPES_MAPPING[klass]
259  else:
260  klass = getattr(swagger_client.models, klass)
261 
262  if klass in self.PRIMITIVE_TYPESPRIMITIVE_TYPES:
263  return self.__deserialize_primitive__deserialize_primitive(data, klass)
264  elif klass == object:
265  return self.__deserialize_object__deserialize_object(data)
266  elif klass == datetime.date:
267  return self.__deserialize_date__deserialize_date(data)
268  elif klass == datetime.datetime:
269  return self.__deserialize_datatime__deserialize_datatime(data)
270  else:
271  return self.__deserialize_model__deserialize_model(data, klass)
272 
273  def call_api(self, resource_path, method,
274  path_params=None, query_params=None, header_params=None,
275  body=None, post_params=None, files=None,
276  response_type=None, auth_settings=None, async_req=None,
277  _return_http_data_only=None, collection_formats=None,
278  _preload_content=True, _request_timeout=None):
279  """Makes the HTTP request (synchronous) and returns deserialized data.
280 
281  To make an async request, set the async_req parameter.
282 
283  :param resource_path: Path to method endpoint.
284  :param method: Method to call.
285  :param path_params: Path parameters in the url.
286  :param query_params: Query parameters in the url.
287  :param header_params: Header parameters to be
288  placed in the request header.
289  :param body: Request body.
290  :param post_params dict: Request post form parameters,
291  for `application/x-www-form-urlencoded`, `multipart/form-data`.
292  :param auth_settings list: Auth Settings names for the request.
293  :param response: Response data type.
294  :param files dict: key -> filename, value -> filepath,
295  for `multipart/form-data`.
296  :param async_req bool: execute request asynchronously
297  :param _return_http_data_only: response data without head status code
298  and headers
299  :param collection_formats: dict of collection formats for path, query,
300  header, and post parameters.
301  :param _preload_content: if False, the urllib3.HTTPResponse object will
302  be returned without reading/decoding response
303  data. Default is True.
304  :param _request_timeout: timeout setting for this request. If one
305  number provided, it will be total request
306  timeout. It can also be a pair (tuple) of
307  (connection, read) timeouts.
308  :return:
309  If async_req parameter is True,
310  the request will be called asynchronously.
311  The method will return the request thread.
312  If parameter async_req is False or missing,
313  then the method will return the response directly.
314  """
315  if not async_req:
316  return self.__call_api__call_api(resource_path, method,
317  path_params, query_params, header_params,
318  body, post_params, files,
319  response_type, auth_settings,
320  _return_http_data_only, collection_formats,
321  _preload_content, _request_timeout)
322  else:
323  thread = self.poolpool.apply_async(self.__call_api__call_api, (resource_path,
324  method, path_params, query_params,
325  header_params, body,
326  post_params, files,
327  response_type, auth_settings,
328  _return_http_data_only,
329  collection_formats,
330  _preload_content, _request_timeout))
331  return thread
332 
333  def request(self, method, url, query_params=None, headers=None,
334  post_params=None, body=None, _preload_content=True,
335  _request_timeout=None):
336  """Makes the HTTP request using RESTClient."""
337  if method == "GET":
338  return self.rest_clientrest_client.GET(url,
339  query_params=query_params,
340  _preload_content=_preload_content,
341  _request_timeout=_request_timeout,
342  headers=headers)
343  elif method == "HEAD":
344  return self.rest_clientrest_client.HEAD(url,
345  query_params=query_params,
346  _preload_content=_preload_content,
347  _request_timeout=_request_timeout,
348  headers=headers)
349  elif method == "OPTIONS":
350  return self.rest_clientrest_client.OPTIONS(url,
351  query_params=query_params,
352  headers=headers,
353  post_params=post_params,
354  _preload_content=_preload_content,
355  _request_timeout=_request_timeout,
356  body=body)
357  elif method == "POST":
358  return self.rest_clientrest_client.POST(url,
359  query_params=query_params,
360  headers=headers,
361  post_params=post_params,
362  _preload_content=_preload_content,
363  _request_timeout=_request_timeout,
364  body=body)
365  elif method == "PUT":
366  return self.rest_clientrest_client.PUT(url,
367  query_params=query_params,
368  headers=headers,
369  post_params=post_params,
370  _preload_content=_preload_content,
371  _request_timeout=_request_timeout,
372  body=body)
373  elif method == "PATCH":
374  return self.rest_clientrest_client.PATCH(url,
375  query_params=query_params,
376  headers=headers,
377  post_params=post_params,
378  _preload_content=_preload_content,
379  _request_timeout=_request_timeout,
380  body=body)
381  elif method == "DELETE":
382  return self.rest_clientrest_client.DELETE(url,
383  query_params=query_params,
384  headers=headers,
385  _preload_content=_preload_content,
386  _request_timeout=_request_timeout,
387  body=body)
388  else:
389  raise ValueError(
390  "http method must be `GET`, `HEAD`, `OPTIONS`,"
391  " `POST`, `PATCH`, `PUT` or `DELETE`."
392  )
393 
394  def parameters_to_tuples(self, params, collection_formats):
395  """Get parameters as list of tuples, formatting collections.
396 
397  :param params: Parameters as dict or list of two-tuples
398  :param dict collection_formats: Parameter collection formats
399  :return: Parameters as list of tuples, collections formatted
400  """
401  new_params = []
402  if collection_formats is None:
403  collection_formats = {}
404  for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501
405  if k in collection_formats:
406  collection_format = collection_formats[k]
407  if collection_format == 'multi':
408  new_params.extend((k, value) for value in v)
409  else:
410  if collection_format == 'ssv':
411  delimiter = ' '
412  elif collection_format == 'tsv':
413  delimiter = '\t'
414  elif collection_format == 'pipes':
415  delimiter = '|'
416  else: # csv is the default
417  delimiter = ','
418  new_params.append(
419  (k, delimiter.join(str(value) for value in v)))
420  else:
421  new_params.append((k, v))
422  return new_params
423 
424  def prepare_post_parameters(self, post_params=None, files=None):
425  """Builds form parameters.
426 
427  :param post_params: Normal form parameters.
428  :param files: File parameters.
429  :return: Form parameters with files.
430  """
431  params = []
432 
433  if post_params:
434  params = post_params
435 
436  if files:
437  for k, v in six.iteritems(files):
438  if not v:
439  continue
440  file_names = v if type(v) is list else [v]
441  for n in file_names:
442  with open(n, 'rb') as f:
443  filename = os.path.basename(f.name)
444  filedata = f.read()
445  mimetype = (mimetypes.guess_type(filename)[0] or
446  'application/octet-stream')
447  params.append(
448  tuple([k, tuple([filename, filedata, mimetype])]))
449 
450  return params
451 
452  def select_header_accept(self, accepts):
453  """Returns `Accept` based on an array of accepts provided.
454 
455  :param accepts: List of headers.
456  :return: Accept (e.g. application/json).
457  """
458  if not accepts:
459  return
460 
461  accepts = [x.lower() for x in accepts]
462 
463  if 'application/json' in accepts:
464  return 'application/json'
465  else:
466  return ', '.join(accepts)
467 
468  def select_header_content_type(self, content_types):
469  """Returns `Content-Type` based on an array of content_types provided.
470 
471  :param content_types: List of content-types.
472  :return: Content-Type (e.g. application/json).
473  """
474  if not content_types:
475  return 'application/json'
476 
477  content_types = [x.lower() for x in content_types]
478 
479  if 'application/json' in content_types or '*/*' in content_types:
480  return 'application/json'
481  else:
482  return content_types[0]
483 
484  def update_params_for_auth(self, headers, querys, auth_settings):
485  """Updates header and query params based on authentication setting.
486 
487  :param headers: Header parameters dict to be updated.
488  :param querys: Query parameters tuple list to be updated.
489  :param auth_settings: Authentication setting identifiers list.
490  """
491  if not auth_settings:
492  return
493 
494  for auth in auth_settings:
495  auth_setting = self.configurationconfiguration.auth_settings().get(auth)
496  if auth_setting:
497  if not auth_setting['value']:
498  continue
499  elif auth_setting['in'] == 'header':
500  headers[auth_setting['key']] = auth_setting['value']
501  elif auth_setting['in'] == 'query':
502  querys.append((auth_setting['key'], auth_setting['value']))
503  else:
504  raise ValueError(
505  'Authentication token must be in `query` or `header`'
506  )
507 
508  def __deserialize_file(self, response):
509  """Deserializes body to file
510 
511  Saves response body into a file in a temporary folder,
512  using the filename from the `Content-Disposition` header if provided.
513 
514  :param response: RESTResponse.
515  :return: file path.
516  """
517  fd, path = tempfile.mkstemp(dir=self.configurationconfiguration.temp_folder_path)
518  os.close(fd)
519  os.remove(path)
520 
521  content_disposition = response.getheader("Content-Disposition")
522  if content_disposition:
523  filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
524  content_disposition).group(1)
525  path = os.path.join(os.path.dirname(path), filename)
526  response_data = response.data
527  with open(path, "wb") as f:
528  if isinstance(response_data, str):
529  # change str to bytes so we can write it
530  response_data = response_data.encode('utf-8')
531  f.write(response_data)
532  else:
533  f.write(response_data)
534  return path
535 
536  def __deserialize_primitive(self, data, klass):
537  """Deserializes string to primitive type.
538 
539  :param data: str.
540  :param klass: class literal.
541 
542  :return: int, long, float, str, bool.
543  """
544  try:
545  return klass(data)
546  except UnicodeEncodeError:
547  return six.text_type(data)
548  except TypeError:
549  return data
550 
551  def __deserialize_object(self, value):
552  """Return a original value.
553 
554  :return: object.
555  """
556  return value
557 
558  def __deserialize_date(self, string):
559  """Deserializes string to date.
560 
561  :param string: str.
562  :return: date.
563  """
564  try:
565  from dateutil.parser import parse
566  return parse(string).date()
567  except ImportError:
568  return string
569  except ValueError:
570  raise rest.ApiException(
571  status=0,
572  reason="Failed to parse `{0}` as date object".format(string)
573  )
574 
575  def __deserialize_datatime(self, string):
576  """Deserializes string to datetime.
577 
578  The string should be in iso8601 datetime format.
579 
580  :param string: str.
581  :return: datetime.
582  """
583  try:
584  from dateutil.parser import parse
585  return parse(string)
586  except ImportError:
587  return string
588  except ValueError:
589  raise rest.ApiException(
590  status=0,
591  reason=(
592  "Failed to parse `{0}` as datetime object"
593  .format(string)
594  )
595  )
596 
597  def __hasattr(self, object, name):
598  return name in object.__class__.__dict__
599 
600  def __deserialize_model(self, data, klass):
601  """Deserializes list or dict to model.
602 
603  :param data: dict, list.
604  :param klass: class literal.
605  :return: model object.
606  """
607 
608  if not klass.swagger_types and not self.__hasattr__hasattr(klass, 'get_real_child_model'):
609  return data
610 
611  kwargs = {}
612  if klass.swagger_types is not None:
613  for attr, attr_type in six.iteritems(klass.swagger_types):
614  if (data is not None and
615  klass.attribute_map[attr] in data and
616  isinstance(data, (list, dict))):
617  value = data[klass.attribute_map[attr]]
618  kwargs[attr] = self.__deserialize__deserialize(value, attr_type)
619 
620  instance = klass(**kwargs)
621 
622  if (isinstance(instance, dict) and
623  klass.swagger_types is not None and
624  isinstance(data, dict)):
625  for key, value in data.items():
626  if key not in klass.swagger_types:
627  instance[key] = value
628  if self.__hasattr__hasattr(instance, 'get_real_child_model'):
629  klass_name = instance.get_real_child_model(data)
630  if klass_name:
631  instance = self.__deserialize__deserialize(data, klass_name)
632  return instance
def set_default_header(self, header_name, header_value)
Definition: api_client.py:90
def update_params_for_auth(self, headers, querys, auth_settings)
Definition: api_client.py:484
def parameters_to_tuples(self, params, collection_formats)
Definition: api_client.py:394
def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None)
Definition: api_client.py:98
def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None)
Definition: api_client.py:63
def prepare_post_parameters(self, post_params=None, files=None)
Definition: api_client.py:424
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None)
Definition: api_client.py:335
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, async_req=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None)
Definition: api_client.py:278
@ DELETE
Definition: nts_types.hpp:382
@ GET
@ POST
@ PUT