diff --git a/.idea/biosim-client.iml b/.idea/biosim-client.iml index ee28fd3..827f278 100644 --- a/.idea/biosim-client.iml +++ b/.idea/biosim-client.iml @@ -1,14 +1,8 @@ - - - - + + - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index d9f9367..8a5e776 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 35eb1dd..94a25f7 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/.openapi-generator-ignore b/.openapi-generator-ignore new file mode 100644 index 0000000..7484ee5 --- /dev/null +++ b/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/.openapi-generator/FILES b/.openapi-generator/FILES new file mode 100644 index 0000000..5c15a2f --- /dev/null +++ b/.openapi-generator/FILES @@ -0,0 +1,48 @@ +.openapi-generator-ignore +biosim_client/__init__.py +biosim_client/simdata_api/__init__.py +biosim_client/simdata_api/api/__init__.py +biosim_client/simdata_api/api/default_api.py +biosim_client/simdata_api/api_client.py +biosim_client/simdata_api/api_response.py +biosim_client/simdata_api/configuration.py +biosim_client/simdata_api/docs/DatasetData.md +biosim_client/simdata_api/docs/DefaultApi.md +biosim_client/simdata_api/docs/HDF5Attribute.md +biosim_client/simdata_api/docs/HDF5Dataset.md +biosim_client/simdata_api/docs/HDF5File.md +biosim_client/simdata_api/docs/HDF5Group.md +biosim_client/simdata_api/docs/HTTPValidationError.md +biosim_client/simdata_api/docs/Status.md +biosim_client/simdata_api/docs/StatusResponse.md +biosim_client/simdata_api/docs/ValidationError.md +biosim_client/simdata_api/docs/ValidationErrorLocInner.md +biosim_client/simdata_api/docs/Value.md +biosim_client/simdata_api/exceptions.py +biosim_client/simdata_api/models/__init__.py +biosim_client/simdata_api/models/dataset_data.py +biosim_client/simdata_api/models/hdf5_attribute.py +biosim_client/simdata_api/models/hdf5_dataset.py +biosim_client/simdata_api/models/hdf5_file.py +biosim_client/simdata_api/models/hdf5_group.py +biosim_client/simdata_api/models/http_validation_error.py +biosim_client/simdata_api/models/status.py +biosim_client/simdata_api/models/status_response.py +biosim_client/simdata_api/models/validation_error.py +biosim_client/simdata_api/models/validation_error_loc_inner.py +biosim_client/simdata_api/models/value.py +biosim_client/simdata_api/rest.py +biosim_client/simdata_api/test/__init__.py +biosim_client/simdata_api/test/test_dataset_data.py +biosim_client/simdata_api/test/test_default_api.py +biosim_client/simdata_api/test/test_hdf5_attribute.py +biosim_client/simdata_api/test/test_hdf5_dataset.py +biosim_client/simdata_api/test/test_hdf5_file.py +biosim_client/simdata_api/test/test_hdf5_group.py +biosim_client/simdata_api/test/test_http_validation_error.py +biosim_client/simdata_api/test/test_status.py +biosim_client/simdata_api/test/test_status_response.py +biosim_client/simdata_api/test/test_validation_error.py +biosim_client/simdata_api/test/test_validation_error_loc_inner.py +biosim_client/simdata_api/test/test_value.py +biosim_client/simdata_api_README.md diff --git a/.openapi-generator/VERSION b/.openapi-generator/VERSION new file mode 100644 index 0000000..4bc5d61 --- /dev/null +++ b/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.9.0 diff --git a/biosim_client/dataset.py b/biosim_client/dataset.py index bef98ef..aa54676 100644 --- a/biosim_client/dataset.py +++ b/biosim_client/dataset.py @@ -3,8 +3,8 @@ import numpy as np import pandas as pd -from biosim_client.api_clients.simdata.openapi_client.models.dataset_data import DatasetData -from biosim_client.api_clients.simdata.openapi_client.models.hdf5_dataset import HDF5Dataset +from biosim_client.simdata_api.models.dataset_data import DatasetData +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset AttributeValueTypes = list[bool] | list[float] | list[int] | list[str] | bool | float | int | str DatasetValueTypes = float | int diff --git a/biosim_client/sim_data.py b/biosim_client/sim_data.py index bc82e5b..543d3a1 100644 --- a/biosim_client/sim_data.py +++ b/biosim_client/sim_data.py @@ -1,7 +1,7 @@ from typing import Optional, get_args -import biosim_client.api_clients.simdata.openapi_client as simdata_client -from biosim_client.api_clients.simdata.openapi_client import HDF5File, DatasetData, HDF5Dataset, Configuration, \ +import biosim_client.simdata_api as simdata_client +from biosim_client.simdata_api import HDF5File, DatasetData, HDF5Dataset, Configuration, \ HDF5Attribute from biosim_client.dataset import Dataset, AttributeValueTypes diff --git a/biosim_client/simdata_api/__init__.py b/biosim_client/simdata_api/__init__.py new file mode 100644 index 0000000..6f69d6a --- /dev/null +++ b/biosim_client/simdata_api/__init__.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +# flake8: noqa + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +__version__ = "1.0.0" + +# import apis into sdk package +from biosim_client.simdata_api.api.default_api import DefaultApi + +# import ApiClient +from biosim_client.simdata_api.api_response import ApiResponse +from biosim_client.simdata_api.api_client import ApiClient +from biosim_client.simdata_api.configuration import Configuration +from biosim_client.simdata_api.exceptions import OpenApiException +from biosim_client.simdata_api.exceptions import ApiTypeError +from biosim_client.simdata_api.exceptions import ApiValueError +from biosim_client.simdata_api.exceptions import ApiKeyError +from biosim_client.simdata_api.exceptions import ApiAttributeError +from biosim_client.simdata_api.exceptions import ApiException + +# import models into sdk package +from biosim_client.simdata_api.models.dataset_data import DatasetData +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset +from biosim_client.simdata_api.models.hdf5_file import HDF5File +from biosim_client.simdata_api.models.hdf5_group import HDF5Group +from biosim_client.simdata_api.models.http_validation_error import HTTPValidationError +from biosim_client.simdata_api.models.status import Status +from biosim_client.simdata_api.models.status_response import StatusResponse +from biosim_client.simdata_api.models.validation_error import ValidationError +from biosim_client.simdata_api.models.validation_error_loc_inner import ValidationErrorLocInner +from biosim_client.simdata_api.models.value import Value + +__all__ = ["DefaultApi", "Configuration", "DatasetData", "HDF5Attribute", "HDF5Dataset", "HDF5File", "StatusResponse"] diff --git a/biosim_client/simdata_api/api/__init__.py b/biosim_client/simdata_api/api/__init__.py new file mode 100644 index 0000000..74b5e69 --- /dev/null +++ b/biosim_client/simdata_api/api/__init__.py @@ -0,0 +1,5 @@ +# flake8: noqa + +# import apis into api package +from biosim_client.simdata_api.api.default_api import DefaultApi + diff --git a/biosim_client/simdata_api/api/default_api.py b/biosim_client/simdata_api/api/default_api.py new file mode 100644 index 0000000..86ac9ae --- /dev/null +++ b/biosim_client/simdata_api/api/default_api.py @@ -0,0 +1,1331 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +import warnings +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated + +from datetime import datetime +from pydantic import StrictStr +from typing import Any +from biosim_client.simdata_api.models.dataset_data import DatasetData +from biosim_client.simdata_api.models.hdf5_file import HDF5File +from biosim_client.simdata_api.models.status_response import StatusResponse + +from biosim_client.simdata_api.api_client import ApiClient, RequestSerialized +from biosim_client.simdata_api.api_response import ApiResponse +from biosim_client.simdata_api.rest import RESTResponseType + + +class DefaultApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def get_health( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> StatusResponse: + """Health + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_health_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StatusResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_health_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[StatusResponse]: + """Health + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_health_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StatusResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_health_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Health + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_health_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StatusResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_health_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/health', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_metadata( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> HDF5File: + """Hdf5 File Metadata + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_metadata_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HDF5File", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_metadata_with_http_info( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HDF5File]: + """Hdf5 File Metadata + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_metadata_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HDF5File", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_metadata_without_preload_content( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Hdf5 File Metadata + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_metadata_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HDF5File", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_metadata_serialize( + self, + run_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if run_id is not None: + _path_params['run_id'] = run_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/datasets/{run_id}/metadata', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def get_modified( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> datetime: + """Modified Datetime + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_modified_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "datetime", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def get_modified_with_http_info( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[datetime]: + """Modified Datetime + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_modified_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "datetime", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_modified_without_preload_content( + self, + run_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Modified Datetime + + + :param run_id: (required) + :type run_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_modified_serialize( + run_id=run_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "datetime", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _get_modified_serialize( + self, + run_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if run_id is not None: + _path_params['run_id'] = run_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/datasets/{run_id}/modified', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def read_dataset( + self, + run_id: StrictStr, + dataset_name: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> DatasetData: + """Read Dataset + + + :param run_id: (required) + :type run_id: str + :param dataset_name: (required) + :type dataset_name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_dataset_serialize( + run_id=run_id, + dataset_name=dataset_name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DatasetData", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def read_dataset_with_http_info( + self, + run_id: StrictStr, + dataset_name: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[DatasetData]: + """Read Dataset + + + :param run_id: (required) + :type run_id: str + :param dataset_name: (required) + :type dataset_name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_dataset_serialize( + run_id=run_id, + dataset_name=dataset_name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DatasetData", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def read_dataset_without_preload_content( + self, + run_id: StrictStr, + dataset_name: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Read Dataset + + + :param run_id: (required) + :type run_id: str + :param dataset_name: (required) + :type dataset_name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._read_dataset_serialize( + run_id=run_id, + dataset_name=dataset_name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "DatasetData", + '404': None, + '422': "HTTPValidationError", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _read_dataset_serialize( + self, + run_id, + dataset_name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if run_id is not None: + _path_params['run_id'] = run_id + # process the query parameters + if dataset_name is not None: + + _query_params.append(('dataset_name', dataset_name)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/datasets/{run_id}/data', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def root_get( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> object: + """Root + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._root_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "object", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def root_get_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[object]: + """Root + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._root_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "object", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def root_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Root + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._root_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "object", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _root_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/biosim_client/simdata_api/api_client.py b/biosim_client/simdata_api/api_client.py new file mode 100644 index 0000000..ab95119 --- /dev/null +++ b/biosim_client/simdata_api/api_client.py @@ -0,0 +1,797 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import datetime +from dateutil.parser import parse +from enum import Enum +import decimal +import json +import mimetypes +import os +import re +import tempfile + +from urllib.parse import quote +from typing import Tuple, Optional, List, Dict, Union +from pydantic import SecretStr + +from biosim_client.simdata_api.configuration import Configuration +from biosim_client.simdata_api.api_response import ApiResponse, T as ApiResponseT +import biosim_client.simdata_api.models +from biosim_client.simdata_api import rest +from biosim_client.simdata_api.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + +class ApiClient: + """Generic API client for OpenAPI client library builds. + + OpenAPI generic API client. This client handles the client- + server communication, and is invariant across implementations. Specifics of + the methods and models for each application are generated from the OpenAPI + templates. + + :param configuration: .Configuration object for this client + :param header_name: a header to pass when making calls to the API. + :param header_value: a header value to pass when making calls to + the API. + :param cookie: a cookie to include in the header when making calls + to the API + """ + + PRIMITIVE_TYPES = (float, bool, bytes, str, int) + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int, # TODO remove as only py3 is supported? + 'float': float, + 'str': str, + 'bool': bool, + 'date': datetime.date, + 'datetime': datetime.datetime, + 'decimal': decimal.Decimal, + 'object': object, + } + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided + if configuration is None: + configuration = Configuration.get_default() + self.configuration = configuration + + self.rest_client = rest.RESTClientObject(configuration) + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.cookie = cookie + # Set default User-Agent. + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + @property + def user_agent(self): + """User agent for this API client""" + return self.default_headers['User-Agent'] + + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value + + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value + + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ + + config = self.configuration + + # header parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) + + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) + for k, v in path_params: + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=config.safe_chars_for_path_param) + ) + + # post parameters + if post_params or files: + post_params = post_params if post_params else [] + post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + if files: + post_params.extend(self.files_parameters(files)) + + # auth setting + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) + + # body + if body: + body = self.sanitize_for_serialization(body) + + # request url + if _host is None or self.configuration.ignore_operation_servers: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query + + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + raise e + + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type, content_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) + + def sanitize_for_serialization(self, obj): + """Builds a JSON POST object. + + If obj is None, return None. + If obj is SecretStr, return obj.get_secret_value() + If obj is str, int, long, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is decimal.Decimal return string representation. + If obj is list, sanitize each element in the list. + If obj is dict, return the dict. + If obj is OpenAPI model, return the properties dict. + + :param obj: The data to serialize. + :return: The serialized form of data. + """ + if obj is None: + return None + elif isinstance(obj, Enum): + return obj.value + elif isinstance(obj, SecretStr): + return obj.get_secret_value() + elif isinstance(obj, self.PRIMITIVE_TYPES): + return obj + elif isinstance(obj, list): + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] + elif isinstance(obj, tuple): + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) + elif isinstance(obj, (datetime.datetime, datetime.date)): + return obj.isoformat() + elif isinstance(obj, decimal.Decimal): + return str(obj) + + elif isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `openapi_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')): + obj_dict = obj.to_dict() + else: + obj_dict = obj.__dict__ + + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } + + def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): + """Deserializes response into an object. + + :param response: RESTResponse object to be deserialized. + :param response_type: class literal for + deserialized object, or string of class name. + :param content_type: content type of response. + + :return: deserialized object. + """ + + # fetch data from response object + if content_type is None: + try: + data = json.loads(response_text) + except ValueError: + data = response_text + elif re.match(r'^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)', content_type, re.IGNORECASE): + if response_text == "": + data = "" + else: + data = json.loads(response_text) + elif re.match(r'^text\/[a-z.+-]+\s*(;|$)', content_type, re.IGNORECASE): + data = response_text + else: + raise ApiException( + status=0, + reason="Unsupported content type: {0}".format(content_type) + ) + + return self.__deserialize(data, response_type) + + def __deserialize(self, data, klass): + """Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if isinstance(klass, str): + if klass.startswith('List['): + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] + + if klass.startswith('Dict['): + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in data.items()} + + # convert str to class + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] + else: + klass = getattr(biosim_client.simdata_api.models, klass) + + if klass in self.PRIMITIVE_TYPES: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object(data) + elif klass == datetime.date: + return self.__deserialize_date(data) + elif klass == datetime.datetime: + return self.__deserialize_datetime(data) + elif klass == decimal.Decimal: + return decimal.Decimal(data) + elif issubclass(klass, Enum): + return self.__deserialize_enum(data, klass) + else: + return self.__deserialize_model(data, klass) + + def parameters_to_tuples(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params: List[Tuple[str, str]] = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, str(value)) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(map(str, item)) for item in new_params]) + + def files_parameters( + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + ): + """Builds form parameters. + + :param files: File parameters. + :return: Form parameters with files. + """ + params = [] + for k, v in files.items(): + if isinstance(v, str): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + elif isinstance(v, bytes): + filename = k + filedata = v + elif isinstance(v, tuple): + filename, filedata = v + elif isinstance(v, list): + for file_param in v: + params.extend(self.files_parameters({k: file_param})) + continue + else: + raise ValueError("Unsupported file value") + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + params.append( + tuple([k, tuple([filename, filedata, mimetype])]) + ) + return params + + def select_header_accept(self, accepts: List[str]) -> Optional[str]: + """Returns `Accept` based on an array of accepts provided. + + :param accepts: List of headers. + :return: Accept (e.g. application/json). + """ + if not accepts: + return None + + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept + + return accepts[0] + + def select_header_content_type(self, content_types): + """Returns `Content-Type` based on an array of content_types provided. + + :param content_types: List of content-types. + :return: Content-Type (e.g. application/json). + """ + if not content_types: + return None + + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. + """ + if not auth_settings: + return + + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """Deserializes body to file + + Saves response body into a file in a temporary folder, + using the filename from the `Content-Disposition` header if provided. + + handle file downloading + save response body into a tmp file and return the instance + + :param response: RESTResponse. + :return: file path. + """ + fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "wb") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """Deserializes string to primitive type. + + :param data: str. + :param klass: class literal. + + :return: int, long, float, str, bool. + """ + try: + return klass(data) + except UnicodeEncodeError: + return str(data) + except TypeError: + return data + + def __deserialize_object(self, value): + """Return an original value. + + :return: object. + """ + return value + + def __deserialize_date(self, string): + """Deserializes string to date. + + :param string: str. + :return: date. + """ + try: + return parse(string).date() + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason="Failed to parse `{0}` as date object".format(string) + ) + + def __deserialize_datetime(self, string): + """Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :return: datetime. + """ + try: + return parse(string) + except ImportError: + return string + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as datetime object" + .format(string) + ) + ) + + def __deserialize_enum(self, data, klass): + """Deserializes primitive type to enum. + + :param data: primitive type. + :param klass: class literal. + :return: enum value. + """ + try: + return klass(data) + except ValueError: + raise rest.ApiException( + status=0, + reason=( + "Failed to parse `{0}` as `{1}`" + .format(data, klass) + ) + ) + + def __deserialize_model(self, data, klass): + """Deserializes list or dict to model. + + :param data: dict, list. + :param klass: class literal. + :return: model object. + """ + + return klass.from_dict(data) diff --git a/biosim_client/simdata_api/api_response.py b/biosim_client/simdata_api/api_response.py new file mode 100644 index 0000000..9bc7c11 --- /dev/null +++ b/biosim_client/simdata_api/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/biosim_client/simdata_api/configuration.py b/biosim_client/simdata_api/configuration.py new file mode 100644 index 0000000..43d016a --- /dev/null +++ b/biosim_client/simdata_api/configuration.py @@ -0,0 +1,450 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import copy +import logging +from logging import FileHandler +import multiprocessing +import sys +from typing import Optional +import urllib3 + +import http.client as httplib + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param ignore_operation_servers + Boolean to ignore operation servers for the API client. + Config will use `host` as the base url regardless of the operation servers. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :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. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + :param retries: Number of retries for API requests. + + """ + + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ignore_operation_servers=False, + ssl_ca_cert=None, + retries=None, + *, + debug: Optional[bool] = None + ) -> None: + """Constructor + """ + self._base_path = "http://localhost" 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.ignore_operation_servers = ignore_operation_servers + """Ignore operation servers + """ + self.temp_folder_path = None + """Temp file folder for downloading files + """ + # Authentication Settings + self.api_key = {} + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = {} + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.refresh_api_key_hook = None + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("biosim_client.simdata_api") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + """Log format + """ + self.logger_stream_handler = None + """Log stream handler + """ + self.logger_file_handler: Optional[FileHandler] = None + """Log file handler + """ + self.logger_file = None + """Debug file location + """ + if debug is not None: + self.debug = debug + else: + self.__debug = False + """Debug switch + """ + + self.verify_ssl = True + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ + self.cert_file = None + """client certificate file + """ + self.key_file = None + """client key file + """ + self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ + + self.proxy: Optional[str] = None + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ + self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = retries + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls): + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = Configuration() + return cls._default + + @property + def logger_file(self): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """The logger file. + + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. + + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug + + @debug.setter + def debug(self, value): + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format + + @logger_format.setter + def logger_format(self, value): + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) + + def get_api_key_with_prefix(self, identifier, alias=None): + """Gets API key (with prefix if set). + + :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. + :return: The token for api key authentication. + """ + if self.refresh_api_key_hook is not None: + self.refresh_api_key_hook(self) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) + if key: + prefix = self.api_key_prefix.get(identifier) + if prefix: + return "%s %s" % (prefix, key) + else: + return key + + def get_basic_auth_token(self): + """Gets HTTP basic authentication header (string). + + :return: The token for basic HTTP authentication. + """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password + return urllib3.util.make_headers( + basic_auth=username + ':' + password + ).get('authorization') + + def auth_settings(self): + """Gets Auth Settings dict for api client. + + :return: The Auth Settings information dict. + """ + auth = {} + return auth + + def to_debug_report(self): + """Gets the essential information for debugging. + + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n"\ + "OS: {env}\n"\ + "Python Version: {pyversion}\n"\ + "Version of the API: 1.0.0\n"\ + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "", + 'description': "No description provided", + } + ] + + 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() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + 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 diff --git a/biosim_client/simdata_api/docs/DatasetData.md b/biosim_client/simdata_api/docs/DatasetData.md new file mode 100644 index 0000000..afb2299 --- /dev/null +++ b/biosim_client/simdata_api/docs/DatasetData.md @@ -0,0 +1,30 @@ +# DatasetData + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shape** | **List[int]** | | +**values** | **List[float]** | | + +## Example + +```python +from biosim_client.simdata_api.models.dataset_data import DatasetData + +# TODO update the JSON string below +json = "{}" +# create an instance of DatasetData from a JSON string +dataset_data_instance = DatasetData.from_json(json) +# print the JSON string representation of the object +print(DatasetData.to_json()) + +# convert the object into a dict +dataset_data_dict = dataset_data_instance.to_dict() +# create an instance of DatasetData from a dict +dataset_data_from_dict = DatasetData.from_dict(dataset_data_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/DefaultApi.md b/biosim_client/simdata_api/docs/DefaultApi.md new file mode 100644 index 0000000..cf7d4a1 --- /dev/null +++ b/biosim_client/simdata_api/docs/DefaultApi.md @@ -0,0 +1,341 @@ +# biosim_client.simdata_api.DefaultApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**get_health**](DefaultApi.md#get_health) | **GET** /health | Health +[**get_metadata**](DefaultApi.md#get_metadata) | **GET** /datasets/{run_id}/metadata | Hdf5 File Metadata +[**get_modified**](DefaultApi.md#get_modified) | **GET** /datasets/{run_id}/modified | Modified Datetime +[**read_dataset**](DefaultApi.md#read_dataset) | **GET** /datasets/{run_id}/data | Read Dataset +[**root_get**](DefaultApi.md#root_get) | **GET** / | Root + + +# **get_health** +> StatusResponse get_health() + +Health + +### Example + + +```python +import biosim_client.simdata_api +from biosim_client.simdata_api.models.status_response import StatusResponse +from biosim_client.simdata_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = biosim_client.simdata_api.Configuration( + host = "http://localhost" +) + + +# Enter a context with an instance of the API client +with biosim_client.simdata_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = biosim_client.simdata_api.DefaultApi(api_client) + + try: + # Health + api_response = api_instance.get_health() + print("The response of DefaultApi->get_health:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_health: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**StatusResponse**](StatusResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_metadata** +> HDF5File get_metadata(run_id) + +Hdf5 File Metadata + +### Example + + +```python +import biosim_client.simdata_api +from biosim_client.simdata_api.models.hdf5_file import HDF5File +from biosim_client.simdata_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = biosim_client.simdata_api.Configuration( + host = "http://localhost" +) + + +# Enter a context with an instance of the API client +with biosim_client.simdata_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = biosim_client.simdata_api.DefaultApi(api_client) + run_id = 'run_id_example' # str | + + try: + # Hdf5 File Metadata + api_response = api_instance.get_metadata(run_id) + print("The response of DefaultApi->get_metadata:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_metadata: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **run_id** | **str**| | + +### Return type + +[**HDF5File**](HDF5File.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | +**404** | Dataset not found | - | +**422** | Validation Error | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **get_modified** +> datetime get_modified(run_id) + +Modified Datetime + +### Example + + +```python +import biosim_client.simdata_api +from biosim_client.simdata_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = biosim_client.simdata_api.Configuration( + host = "http://localhost" +) + + +# Enter a context with an instance of the API client +with biosim_client.simdata_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = biosim_client.simdata_api.DefaultApi(api_client) + run_id = 'run_id_example' # str | + + try: + # Modified Datetime + api_response = api_instance.get_modified(run_id) + print("The response of DefaultApi->get_modified:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->get_modified: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **run_id** | **str**| | + +### Return type + +**datetime** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | +**404** | Dataset not found | - | +**422** | Validation Error | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **read_dataset** +> DatasetData read_dataset(run_id, dataset_name) + +Read Dataset + +### Example + + +```python +import biosim_client.simdata_api +from biosim_client.simdata_api.models.dataset_data import DatasetData +from biosim_client.simdata_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = biosim_client.simdata_api.Configuration( + host = "http://localhost" +) + + +# Enter a context with an instance of the API client +with biosim_client.simdata_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = biosim_client.simdata_api.DefaultApi(api_client) + run_id = 'run_id_example' # str | + dataset_name = 'dataset_name_example' # str | + + try: + # Read Dataset + api_response = api_instance.read_dataset(run_id, dataset_name) + print("The response of DefaultApi->read_dataset:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->read_dataset: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **run_id** | **str**| | + **dataset_name** | **str**| | + +### Return type + +[**DatasetData**](DatasetData.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | +**404** | Dataset not found | - | +**422** | Validation Error | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **root_get** +> object root_get() + +Root + +### Example + + +```python +import biosim_client.simdata_api +from biosim_client.simdata_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost +# See configuration.py for a list of all supported configuration parameters. +configuration = biosim_client.simdata_api.Configuration( + host = "http://localhost" +) + + +# Enter a context with an instance of the API client +with biosim_client.simdata_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = biosim_client.simdata_api.DefaultApi(api_client) + + try: + # Root + api_response = api_instance.root_get() + print("The response of DefaultApi->root_get:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling DefaultApi->root_get: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful Response | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/biosim_client/simdata_api/docs/HDF5Attribute.md b/biosim_client/simdata_api/docs/HDF5Attribute.md new file mode 100644 index 0000000..43d3ea9 --- /dev/null +++ b/biosim_client/simdata_api/docs/HDF5Attribute.md @@ -0,0 +1,30 @@ +# HDF5Attribute + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**key** | **str** | | +**value** | [**Value**](Value.md) | | + +## Example + +```python +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute + +# TODO update the JSON string below +json = "{}" +# create an instance of HDF5Attribute from a JSON string +hdf5_attribute_instance = HDF5Attribute.from_json(json) +# print the JSON string representation of the object +print(HDF5Attribute.to_json()) + +# convert the object into a dict +hdf5_attribute_dict = hdf5_attribute_instance.to_dict() +# create an instance of HDF5Attribute from a dict +hdf5_attribute_from_dict = HDF5Attribute.from_dict(hdf5_attribute_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/HDF5Dataset.md b/biosim_client/simdata_api/docs/HDF5Dataset.md new file mode 100644 index 0000000..dc037e0 --- /dev/null +++ b/biosim_client/simdata_api/docs/HDF5Dataset.md @@ -0,0 +1,31 @@ +# HDF5Dataset + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | +**shape** | **List[int]** | | +**attributes** | [**List[HDF5Attribute]**](HDF5Attribute.md) | | + +## Example + +```python +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset + +# TODO update the JSON string below +json = "{}" +# create an instance of HDF5Dataset from a JSON string +hdf5_dataset_instance = HDF5Dataset.from_json(json) +# print the JSON string representation of the object +print(HDF5Dataset.to_json()) + +# convert the object into a dict +hdf5_dataset_dict = hdf5_dataset_instance.to_dict() +# create an instance of HDF5Dataset from a dict +hdf5_dataset_from_dict = HDF5Dataset.from_dict(hdf5_dataset_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/HDF5File.md b/biosim_client/simdata_api/docs/HDF5File.md new file mode 100644 index 0000000..837a1f4 --- /dev/null +++ b/biosim_client/simdata_api/docs/HDF5File.md @@ -0,0 +1,32 @@ +# HDF5File + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**filename** | **str** | | +**id** | **str** | | +**uri** | **str** | | +**groups** | [**List[HDF5Group]**](HDF5Group.md) | | + +## Example + +```python +from biosim_client.simdata_api.models.hdf5_file import HDF5File + +# TODO update the JSON string below +json = "{}" +# create an instance of HDF5File from a JSON string +hdf5_file_instance = HDF5File.from_json(json) +# print the JSON string representation of the object +print(HDF5File.to_json()) + +# convert the object into a dict +hdf5_file_dict = hdf5_file_instance.to_dict() +# create an instance of HDF5File from a dict +hdf5_file_from_dict = HDF5File.from_dict(hdf5_file_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/HDF5Group.md b/biosim_client/simdata_api/docs/HDF5Group.md new file mode 100644 index 0000000..7bb697a --- /dev/null +++ b/biosim_client/simdata_api/docs/HDF5Group.md @@ -0,0 +1,31 @@ +# HDF5Group + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | +**attributes** | [**List[HDF5Attribute]**](HDF5Attribute.md) | | +**datasets** | [**List[HDF5Dataset]**](HDF5Dataset.md) | | + +## Example + +```python +from biosim_client.simdata_api.models.hdf5_group import HDF5Group + +# TODO update the JSON string below +json = "{}" +# create an instance of HDF5Group from a JSON string +hdf5_group_instance = HDF5Group.from_json(json) +# print the JSON string representation of the object +print(HDF5Group.to_json()) + +# convert the object into a dict +hdf5_group_dict = hdf5_group_instance.to_dict() +# create an instance of HDF5Group from a dict +hdf5_group_from_dict = HDF5Group.from_dict(hdf5_group_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/HTTPValidationError.md b/biosim_client/simdata_api/docs/HTTPValidationError.md new file mode 100644 index 0000000..3bd1fe4 --- /dev/null +++ b/biosim_client/simdata_api/docs/HTTPValidationError.md @@ -0,0 +1,29 @@ +# HTTPValidationError + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**detail** | [**List[ValidationError]**](ValidationError.md) | | [optional] + +## Example + +```python +from biosim_client.simdata_api.models.http_validation_error import HTTPValidationError + +# TODO update the JSON string below +json = "{}" +# create an instance of HTTPValidationError from a JSON string +http_validation_error_instance = HTTPValidationError.from_json(json) +# print the JSON string representation of the object +print(HTTPValidationError.to_json()) + +# convert the object into a dict +http_validation_error_dict = http_validation_error_instance.to_dict() +# create an instance of HTTPValidationError from a dict +http_validation_error_from_dict = HTTPValidationError.from_dict(http_validation_error_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/Status.md b/biosim_client/simdata_api/docs/Status.md new file mode 100644 index 0000000..6a2f3da --- /dev/null +++ b/biosim_client/simdata_api/docs/Status.md @@ -0,0 +1,12 @@ +# Status + + +## Enum + +* `OK` (value: `'ok'`) + +* `ERROR` (value: `'error'`) + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/StatusResponse.md b/biosim_client/simdata_api/docs/StatusResponse.md new file mode 100644 index 0000000..d3b7710 --- /dev/null +++ b/biosim_client/simdata_api/docs/StatusResponse.md @@ -0,0 +1,29 @@ +# StatusResponse + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**status** | [**Status**](Status.md) | | + +## Example + +```python +from biosim_client.simdata_api.models.status_response import StatusResponse + +# TODO update the JSON string below +json = "{}" +# create an instance of StatusResponse from a JSON string +status_response_instance = StatusResponse.from_json(json) +# print the JSON string representation of the object +print(StatusResponse.to_json()) + +# convert the object into a dict +status_response_dict = status_response_instance.to_dict() +# create an instance of StatusResponse from a dict +status_response_from_dict = StatusResponse.from_dict(status_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/ValidationError.md b/biosim_client/simdata_api/docs/ValidationError.md new file mode 100644 index 0000000..c1ec894 --- /dev/null +++ b/biosim_client/simdata_api/docs/ValidationError.md @@ -0,0 +1,31 @@ +# ValidationError + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**loc** | [**List[ValidationErrorLocInner]**](ValidationErrorLocInner.md) | | +**msg** | **str** | | +**type** | **str** | | + +## Example + +```python +from biosim_client.simdata_api.models.validation_error import ValidationError + +# TODO update the JSON string below +json = "{}" +# create an instance of ValidationError from a JSON string +validation_error_instance = ValidationError.from_json(json) +# print the JSON string representation of the object +print(ValidationError.to_json()) + +# convert the object into a dict +validation_error_dict = validation_error_instance.to_dict() +# create an instance of ValidationError from a dict +validation_error_from_dict = ValidationError.from_dict(validation_error_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/ValidationErrorLocInner.md b/biosim_client/simdata_api/docs/ValidationErrorLocInner.md new file mode 100644 index 0000000..97fd9b5 --- /dev/null +++ b/biosim_client/simdata_api/docs/ValidationErrorLocInner.md @@ -0,0 +1,28 @@ +# ValidationErrorLocInner + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from biosim_client.simdata_api.models.validation_error_loc_inner import ValidationErrorLocInner + +# TODO update the JSON string below +json = "{}" +# create an instance of ValidationErrorLocInner from a JSON string +validation_error_loc_inner_instance = ValidationErrorLocInner.from_json(json) +# print the JSON string representation of the object +print(ValidationErrorLocInner.to_json()) + +# convert the object into a dict +validation_error_loc_inner_dict = validation_error_loc_inner_instance.to_dict() +# create an instance of ValidationErrorLocInner from a dict +validation_error_loc_inner_from_dict = ValidationErrorLocInner.from_dict(validation_error_loc_inner_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/docs/Value.md b/biosim_client/simdata_api/docs/Value.md new file mode 100644 index 0000000..7c363cb --- /dev/null +++ b/biosim_client/simdata_api/docs/Value.md @@ -0,0 +1,28 @@ +# Value + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Example + +```python +from biosim_client.simdata_api.models.value import Value + +# TODO update the JSON string below +json = "{}" +# create an instance of Value from a JSON string +value_instance = Value.from_json(json) +# print the JSON string representation of the object +print(Value.to_json()) + +# convert the object into a dict +value_dict = value_instance.to_dict() +# create an instance of Value from a dict +value_from_dict = Value.from_dict(value_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/biosim_client/simdata_api/exceptions.py b/biosim_client/simdata_api/exceptions.py new file mode 100644 index 0000000..cf8e9cc --- /dev/null +++ b/biosim_client/simdata_api/exceptions.py @@ -0,0 +1,199 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from typing import Any, Optional +from typing_extensions import Self + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message + + +class BadRequestException(ApiException): + pass + + +class NotFoundException(ApiException): + pass + + +class UnauthorizedException(ApiException): + pass + + +class ForbiddenException(ApiException): + pass + + +class ServiceException(ApiException): + pass + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/biosim_client/simdata_api/models/__init__.py b/biosim_client/simdata_api/models/__init__.py new file mode 100644 index 0000000..62810e8 --- /dev/null +++ b/biosim_client/simdata_api/models/__init__.py @@ -0,0 +1,27 @@ +# coding: utf-8 + +# flake8: noqa +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +# import models into model package +from biosim_client.simdata_api.models.dataset_data import DatasetData +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset +from biosim_client.simdata_api.models.hdf5_file import HDF5File +from biosim_client.simdata_api.models.hdf5_group import HDF5Group +from biosim_client.simdata_api.models.http_validation_error import HTTPValidationError +from biosim_client.simdata_api.models.status import Status +from biosim_client.simdata_api.models.status_response import StatusResponse +from biosim_client.simdata_api.models.validation_error import ValidationError +from biosim_client.simdata_api.models.validation_error_loc_inner import ValidationErrorLocInner +from biosim_client.simdata_api.models.value import Value diff --git a/biosim_client/simdata_api/models/dataset_data.py b/biosim_client/simdata_api/models/dataset_data.py new file mode 100644 index 0000000..5ff4052 --- /dev/null +++ b/biosim_client/simdata_api/models/dataset_data.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Union +from typing import Optional, Set +from typing_extensions import Self + +class DatasetData(BaseModel): + """ + DatasetData + """ # noqa: E501 + shape: List[StrictInt] + values: List[Union[StrictFloat, StrictInt]] + __properties: ClassVar[List[str]] = ["shape", "values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of DatasetData from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of DatasetData from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "shape": obj.get("shape"), + "values": obj.get("values") + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/hdf5_attribute.py b/biosim_client/simdata_api/models/hdf5_attribute.py new file mode 100644 index 0000000..fdbec26 --- /dev/null +++ b/biosim_client/simdata_api/models/hdf5_attribute.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.value import Value +from typing import Optional, Set +from typing_extensions import Self + +class HDF5Attribute(BaseModel): + """ + HDF5Attribute + """ # noqa: E501 + key: StrictStr + value: Value + __properties: ClassVar[List[str]] = ["key", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HDF5Attribute from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of value + if self.value: + _dict['value'] = self.value.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HDF5Attribute from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "value": Value.from_dict(obj["value"]) if obj.get("value") is not None else None + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/hdf5_dataset.py b/biosim_client/simdata_api/models/hdf5_dataset.py new file mode 100644 index 0000000..de48804 --- /dev/null +++ b/biosim_client/simdata_api/models/hdf5_dataset.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute +from typing import Optional, Set +from typing_extensions import Self + +class HDF5Dataset(BaseModel): + """ + HDF5Dataset + """ # noqa: E501 + name: StrictStr + shape: List[StrictInt] + attributes: List[HDF5Attribute] + __properties: ClassVar[List[str]] = ["name", "shape", "attributes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HDF5Dataset from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in attributes (list) + _items = [] + if self.attributes: + for _item_attributes in self.attributes: + if _item_attributes: + _items.append(_item_attributes.to_dict()) + _dict['attributes'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HDF5Dataset from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "shape": obj.get("shape"), + "attributes": [HDF5Attribute.from_dict(_item) for _item in obj["attributes"]] if obj.get("attributes") is not None else None + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/hdf5_file.py b/biosim_client/simdata_api/models/hdf5_file.py new file mode 100644 index 0000000..7e2e2b2 --- /dev/null +++ b/biosim_client/simdata_api/models/hdf5_file.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.hdf5_group import HDF5Group +from typing import Optional, Set +from typing_extensions import Self + +class HDF5File(BaseModel): + """ + HDF5File + """ # noqa: E501 + filename: StrictStr + id: StrictStr + uri: StrictStr + groups: List[HDF5Group] + __properties: ClassVar[List[str]] = ["filename", "id", "uri", "groups"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HDF5File from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in groups (list) + _items = [] + if self.groups: + for _item_groups in self.groups: + if _item_groups: + _items.append(_item_groups.to_dict()) + _dict['groups'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HDF5File from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "filename": obj.get("filename"), + "id": obj.get("id"), + "uri": obj.get("uri"), + "groups": [HDF5Group.from_dict(_item) for _item in obj["groups"]] if obj.get("groups") is not None else None + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/hdf5_group.py b/biosim_client/simdata_api/models/hdf5_group.py new file mode 100644 index 0000000..b375345 --- /dev/null +++ b/biosim_client/simdata_api/models/hdf5_group.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset +from typing import Optional, Set +from typing_extensions import Self + +class HDF5Group(BaseModel): + """ + HDF5Group + """ # noqa: E501 + name: StrictStr + attributes: List[HDF5Attribute] + datasets: List[HDF5Dataset] + __properties: ClassVar[List[str]] = ["name", "attributes", "datasets"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HDF5Group from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in attributes (list) + _items = [] + if self.attributes: + for _item_attributes in self.attributes: + if _item_attributes: + _items.append(_item_attributes.to_dict()) + _dict['attributes'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in datasets (list) + _items = [] + if self.datasets: + for _item_datasets in self.datasets: + if _item_datasets: + _items.append(_item_datasets.to_dict()) + _dict['datasets'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HDF5Group from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "attributes": [HDF5Attribute.from_dict(_item) for _item in obj["attributes"]] if obj.get("attributes") is not None else None, + "datasets": [HDF5Dataset.from_dict(_item) for _item in obj["datasets"]] if obj.get("datasets") is not None else None + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/http_validation_error.py b/biosim_client/simdata_api/models/http_validation_error.py new file mode 100644 index 0000000..d6683f2 --- /dev/null +++ b/biosim_client/simdata_api/models/http_validation_error.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from biosim_client.simdata_api.models.validation_error import ValidationError +from typing import Optional, Set +from typing_extensions import Self + +class HTTPValidationError(BaseModel): + """ + HTTPValidationError + """ # noqa: E501 + detail: Optional[List[ValidationError]] = None + __properties: ClassVar[List[str]] = ["detail"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of HTTPValidationError from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in detail (list) + _items = [] + if self.detail: + for _item_detail in self.detail: + if _item_detail: + _items.append(_item_detail.to_dict()) + _dict['detail'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of HTTPValidationError from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "detail": [ValidationError.from_dict(_item) for _item in obj["detail"]] if obj.get("detail") is not None else None + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/status.py b/biosim_client/simdata_api/models/status.py new file mode 100644 index 0000000..d3503ac --- /dev/null +++ b/biosim_client/simdata_api/models/status.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +from enum import Enum +from typing_extensions import Self + + +class Status(str, Enum): + """ + Status + """ + + """ + allowed enum values + """ + OK = 'ok' + ERROR = 'error' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Status from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/biosim_client/simdata_api/models/status_response.py b/biosim_client/simdata_api/models/status_response.py new file mode 100644 index 0000000..134f7da --- /dev/null +++ b/biosim_client/simdata_api/models/status_response.py @@ -0,0 +1,88 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.status import Status +from typing import Optional, Set +from typing_extensions import Self + +class StatusResponse(BaseModel): + """ + StatusResponse + """ # noqa: E501 + status: Status + __properties: ClassVar[List[str]] = ["status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of StatusResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of StatusResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status") + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/validation_error.py b/biosim_client/simdata_api/models/validation_error.py new file mode 100644 index 0000000..ecbbd61 --- /dev/null +++ b/biosim_client/simdata_api/models/validation_error.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List +from biosim_client.simdata_api.models.validation_error_loc_inner import ValidationErrorLocInner +from typing import Optional, Set +from typing_extensions import Self + +class ValidationError(BaseModel): + """ + ValidationError + """ # noqa: E501 + loc: List[ValidationErrorLocInner] + msg: StrictStr + type: StrictStr + __properties: ClassVar[List[str]] = ["loc", "msg", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ValidationError from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in loc (list) + _items = [] + if self.loc: + for _item_loc in self.loc: + if _item_loc: + _items.append(_item_loc.to_dict()) + _dict['loc'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ValidationError from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "loc": [ValidationErrorLocInner.from_dict(_item) for _item in obj["loc"]] if obj.get("loc") is not None else None, + "msg": obj.get("msg"), + "type": obj.get("type") + }) + return _obj + + diff --git a/biosim_client/simdata_api/models/validation_error_loc_inner.py b/biosim_client/simdata_api/models/validation_error_loc_inner.py new file mode 100644 index 0000000..69b018c --- /dev/null +++ b/biosim_client/simdata_api/models/validation_error_loc_inner.py @@ -0,0 +1,138 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError, field_validator +from typing import Optional +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field + +VALIDATIONERRORLOCINNER_ANY_OF_SCHEMAS = ["int", "str"] + +class ValidationErrorLocInner(BaseModel): + """ + ValidationErrorLocInner + """ + + # data type: str + anyof_schema_1_validator: Optional[StrictStr] = None + # data type: int + anyof_schema_2_validator: Optional[StrictInt] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[int, str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "int", "str" } + + model_config = { + "validate_assignment": True, + "protected_namespaces": (), + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_anyof(cls, v): + instance = ValidationErrorLocInner.model_construct() + error_messages = [] + # validate data type: str + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: int + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in ValidationErrorLocInner with anyOf schemas: int, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + # deserialize data into str + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into int + try: + # validation + instance.anyof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into ValidationErrorLocInner with anyOf schemas: int, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/biosim_client/simdata_api/models/value.py b/biosim_client/simdata_api/models/value.py new file mode 100644 index 0000000..b087f8c --- /dev/null +++ b/biosim_client/simdata_api/models/value.py @@ -0,0 +1,240 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, ValidationError, field_validator +from typing import List, Optional, Union +from typing import Union, Any, List, Set, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal, Self +from pydantic import Field + +VALUE_ANY_OF_SCHEMAS = ["List[bool]", "List[float]", "List[int]", "List[str]", "bool", "float", "int", "str"] + +class Value(BaseModel): + """ + Value + """ + + # data type: int + anyof_schema_1_validator: Optional[StrictInt] = None + # data type: float + anyof_schema_2_validator: Optional[Union[StrictFloat, StrictInt]] = None + # data type: str + anyof_schema_3_validator: Optional[StrictStr] = None + # data type: bool + anyof_schema_4_validator: Optional[StrictBool] = None + # data type: List[str] + anyof_schema_5_validator: Optional[List[StrictStr]] = None + # data type: List[int] + anyof_schema_6_validator: Optional[List[StrictInt]] = None + # data type: List[float] + anyof_schema_7_validator: Optional[List[Union[StrictFloat, StrictInt]]] = None + # data type: List[bool] + anyof_schema_8_validator: Optional[List[StrictBool]] = None + if TYPE_CHECKING: + actual_instance: Optional[Union[List[bool], List[float], List[int], List[str], bool, float, int, str]] = None + else: + actual_instance: Any = None + any_of_schemas: Set[str] = { "List[bool]", "List[float]", "List[int]", "List[str]", "bool", "float", "int", "str" } + + model_config = { + "validate_assignment": True, + "protected_namespaces": (), + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_anyof(cls, v): + instance = Value.model_construct() + error_messages = [] + # validate data type: int + try: + instance.anyof_schema_1_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: float + try: + instance.anyof_schema_2_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: str + try: + instance.anyof_schema_3_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: bool + try: + instance.anyof_schema_4_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[str] + try: + instance.anyof_schema_5_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[int] + try: + instance.anyof_schema_6_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[float] + try: + instance.anyof_schema_7_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # validate data type: List[bool] + try: + instance.anyof_schema_8_validator = v + return v + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + if error_messages: + # no match + raise ValueError("No match found when setting the actual_instance in Value with anyOf schemas: List[bool], List[float], List[int], List[str], bool, float, int, str. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: Dict[str, Any]) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + # deserialize data into int + try: + # validation + instance.anyof_schema_1_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_1_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into float + try: + # validation + instance.anyof_schema_2_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_2_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into str + try: + # validation + instance.anyof_schema_3_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_3_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into bool + try: + # validation + instance.anyof_schema_4_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_4_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[str] + try: + # validation + instance.anyof_schema_5_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_5_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[int] + try: + # validation + instance.anyof_schema_6_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_6_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[float] + try: + # validation + instance.anyof_schema_7_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_7_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into List[bool] + try: + # validation + instance.anyof_schema_8_validator = json.loads(json_str) + # assign value to actual_instance + instance.actual_instance = instance.anyof_schema_8_validator + return instance + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if error_messages: + # no match + raise ValueError("No match found when deserializing the JSON string into Value with anyOf schemas: List[bool], List[float], List[int], List[str], bool, float, int, str. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Optional[Union[Dict[str, Any], List[bool], List[float], List[int], List[str], bool, float, int, str]]: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): + return self.actual_instance.to_dict() + else: + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/biosim_client/simdata_api/rest.py b/biosim_client/simdata_api/rest.py new file mode 100644 index 0000000..dae356e --- /dev/null +++ b/biosim_client/simdata_api/rest.py @@ -0,0 +1,257 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import json +import re +import ssl + +import urllib3 + +from biosim_client.simdata_api.exceptions import ApiException, ApiValueError + +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data + + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 + + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/biosim_client/simdata_api/test/__init__.py b/biosim_client/simdata_api/test/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/biosim_client/simdata_api/test/test_dataset_data.py b/biosim_client/simdata_api/test/test_dataset_data.py new file mode 100644 index 0000000..b67f974 --- /dev/null +++ b/biosim_client/simdata_api/test/test_dataset_data.py @@ -0,0 +1,62 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.dataset_data import DatasetData + +class TestDatasetData(unittest.TestCase): + """DatasetData unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> DatasetData: + """Test DatasetData + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `DatasetData` + """ + model = DatasetData() + if include_optional: + return DatasetData( + shape = [ + 56 + ], + values = [ + 1.337 + ] + ) + else: + return DatasetData( + shape = [ + 56 + ], + values = [ + 1.337 + ], + ) + """ + + def testDatasetData(self): + """Test DatasetData""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_default_api.py b/biosim_client/simdata_api/test/test_default_api.py new file mode 100644 index 0000000..2dc41cc --- /dev/null +++ b/biosim_client/simdata_api/test/test_default_api.py @@ -0,0 +1,66 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.api.default_api import DefaultApi + + +class TestDefaultApi(unittest.TestCase): + """DefaultApi unit test stubs""" + + def setUp(self) -> None: + self.api = DefaultApi() + + def tearDown(self) -> None: + pass + + def test_get_health(self) -> None: + """Test case for get_health + + Health + """ + pass + + def test_get_metadata(self) -> None: + """Test case for get_metadata + + Hdf5 File Metadata + """ + pass + + def test_get_modified(self) -> None: + """Test case for get_modified + + Modified Datetime + """ + pass + + def test_read_dataset(self) -> None: + """Test case for read_dataset + + Read Dataset + """ + pass + + def test_root_get(self) -> None: + """Test case for root_get + + Root + """ + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_hdf5_attribute.py b/biosim_client/simdata_api/test/test_hdf5_attribute.py new file mode 100644 index 0000000..77a36b6 --- /dev/null +++ b/biosim_client/simdata_api/test/test_hdf5_attribute.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.hdf5_attribute import HDF5Attribute + +class TestHDF5Attribute(unittest.TestCase): + """HDF5Attribute unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> HDF5Attribute: + """Test HDF5Attribute + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `HDF5Attribute` + """ + model = HDF5Attribute() + if include_optional: + return HDF5Attribute( + key = '', + value = None + ) + else: + return HDF5Attribute( + key = '', + value = None, + ) + """ + + def testHDF5Attribute(self): + """Test HDF5Attribute""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_hdf5_dataset.py b/biosim_client/simdata_api/test/test_hdf5_dataset.py new file mode 100644 index 0000000..527ad17 --- /dev/null +++ b/biosim_client/simdata_api/test/test_hdf5_dataset.py @@ -0,0 +1,68 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.hdf5_dataset import HDF5Dataset + +class TestHDF5Dataset(unittest.TestCase): + """HDF5Dataset unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> HDF5Dataset: + """Test HDF5Dataset + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `HDF5Dataset` + """ + model = HDF5Dataset() + if include_optional: + return HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ] + ) + else: + return HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], + ) + """ + + def testHDF5Dataset(self): + """Test HDF5Dataset""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_hdf5_file.py b/biosim_client/simdata_api/test/test_hdf5_file.py new file mode 100644 index 0000000..37484e3 --- /dev/null +++ b/biosim_client/simdata_api/test/test_hdf5_file.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.hdf5_file import HDF5File + +class TestHDF5File(unittest.TestCase): + """HDF5File unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> HDF5File: + """Test HDF5File + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `HDF5File` + """ + model = HDF5File() + if include_optional: + return HDF5File( + filename = '', + id = '', + uri = '', + groups = [ + biosim_client.simdata_api.models.hdf5_group.HDF5Group( + name = '', + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], + datasets = [ + biosim_client.simdata_api.models.hdf5_dataset.HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], ) + ], ) + ] + ) + else: + return HDF5File( + filename = '', + id = '', + uri = '', + groups = [ + biosim_client.simdata_api.models.hdf5_group.HDF5Group( + name = '', + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], + datasets = [ + biosim_client.simdata_api.models.hdf5_dataset.HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], ) + ], ) + ], + ) + """ + + def testHDF5File(self): + """Test HDF5File""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_hdf5_group.py b/biosim_client/simdata_api/test/test_hdf5_group.py new file mode 100644 index 0000000..62c631a --- /dev/null +++ b/biosim_client/simdata_api/test/test_hdf5_group.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.hdf5_group import HDF5Group + +class TestHDF5Group(unittest.TestCase): + """HDF5Group unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> HDF5Group: + """Test HDF5Group + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `HDF5Group` + """ + model = HDF5Group() + if include_optional: + return HDF5Group( + name = '', + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], + datasets = [ + biosim_client.simdata_api.models.hdf5_dataset.HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], ) + ] + ) + else: + return HDF5Group( + name = '', + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], + datasets = [ + biosim_client.simdata_api.models.hdf5_dataset.HDF5Dataset( + name = '', + shape = [ + 56 + ], + attributes = [ + biosim_client.simdata_api.models.hdf5_attribute.HDF5Attribute( + key = '', + value = null, ) + ], ) + ], + ) + """ + + def testHDF5Group(self): + """Test HDF5Group""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_http_validation_error.py b/biosim_client/simdata_api/test/test_http_validation_error.py new file mode 100644 index 0000000..ea2301e --- /dev/null +++ b/biosim_client/simdata_api/test/test_http_validation_error.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.http_validation_error import HTTPValidationError + +class TestHTTPValidationError(unittest.TestCase): + """HTTPValidationError unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> HTTPValidationError: + """Test HTTPValidationError + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `HTTPValidationError` + """ + model = HTTPValidationError() + if include_optional: + return HTTPValidationError( + detail = [ + biosim_client.simdata_api.models.validation_error.ValidationError( + loc = [ + null + ], + msg = '', + type = '', ) + ] + ) + else: + return HTTPValidationError( + ) + """ + + def testHTTPValidationError(self): + """Test HTTPValidationError""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_status.py b/biosim_client/simdata_api/test/test_status.py new file mode 100644 index 0000000..d7b7277 --- /dev/null +++ b/biosim_client/simdata_api/test/test_status.py @@ -0,0 +1,33 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.status import Status + +class TestStatus(unittest.TestCase): + """Status unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testStatus(self): + """Test Status""" + # inst = Status() + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_status_response.py b/biosim_client/simdata_api/test/test_status_response.py new file mode 100644 index 0000000..a2c3cf1 --- /dev/null +++ b/biosim_client/simdata_api/test/test_status_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.status_response import StatusResponse + +class TestStatusResponse(unittest.TestCase): + """StatusResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> StatusResponse: + """Test StatusResponse + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `StatusResponse` + """ + model = StatusResponse() + if include_optional: + return StatusResponse( + status = 'ok' + ) + else: + return StatusResponse( + status = 'ok', + ) + """ + + def testStatusResponse(self): + """Test StatusResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_validation_error.py b/biosim_client/simdata_api/test/test_validation_error.py new file mode 100644 index 0000000..0aeca0e --- /dev/null +++ b/biosim_client/simdata_api/test/test_validation_error.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.validation_error import ValidationError + +class TestValidationError(unittest.TestCase): + """ValidationError unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ValidationError: + """Test ValidationError + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ValidationError` + """ + model = ValidationError() + if include_optional: + return ValidationError( + loc = [ + null + ], + msg = '', + type = '' + ) + else: + return ValidationError( + loc = [ + null + ], + msg = '', + type = '', + ) + """ + + def testValidationError(self): + """Test ValidationError""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_validation_error_loc_inner.py b/biosim_client/simdata_api/test/test_validation_error_loc_inner.py new file mode 100644 index 0000000..72842a7 --- /dev/null +++ b/biosim_client/simdata_api/test/test_validation_error_loc_inner.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.validation_error_loc_inner import ValidationErrorLocInner + +class TestValidationErrorLocInner(unittest.TestCase): + """ValidationErrorLocInner unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ValidationErrorLocInner: + """Test ValidationErrorLocInner + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ValidationErrorLocInner` + """ + model = ValidationErrorLocInner() + if include_optional: + return ValidationErrorLocInner( + ) + else: + return ValidationErrorLocInner( + ) + """ + + def testValidationErrorLocInner(self): + """Test ValidationErrorLocInner""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdata_api/test/test_value.py b/biosim_client/simdata_api/test/test_value.py new file mode 100644 index 0000000..e39dabc --- /dev/null +++ b/biosim_client/simdata_api/test/test_value.py @@ -0,0 +1,50 @@ +# coding: utf-8 + +""" + simdata-api + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from biosim_client.simdata_api.models.value import Value + +class TestValue(unittest.TestCase): + """Value unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> Value: + """Test Value + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `Value` + """ + model = Value() + if include_optional: + return Value( + ) + else: + return Value( + ) + """ + + def testValue(self): + """Test Value""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/biosim_client/simdataclient.py b/biosim_client/simdataclient.py index 6128e5a..39c49e4 100644 --- a/biosim_client/simdataclient.py +++ b/biosim_client/simdataclient.py @@ -1,6 +1,6 @@ -import biosim_client.api_clients.simdata.openapi_client as simdata_client -from biosim_client.api_clients.simdata.openapi_client import StatusResponse, HDF5File -from biosim_client.api_clients.simdata.openapi_client.configuration import Configuration +import biosim_client.simdata_api as simdata_client +from biosim_client.simdata_api import StatusResponse, HDF5File +from biosim_client.simdata_api.configuration import Configuration from biosim_client.sim_data import SimData diff --git a/pyproject.toml b/pyproject.toml index d54b62c..fc6abf7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ build-backend = "poetry.core.masonry.api" [tool.mypy] files = ["biosim_client"] +explicit_package_bases = "True" disallow_untyped_defs = "True" disallow_any_unimported = "True" no_implicit_optional = "True" @@ -47,7 +48,13 @@ warn_return_any = "True" warn_unused_ignores = "True" show_error_codes = "True" +[[tool.mypy.overrides]] +module = [ "biosim_client.simdata_api.*" ] +disable_error_code = ["no-untyped-def", "no-any-return", "var-annotated"] +[[tool.mypy.overrides]] +module = [ "biosim_client.simdata_api.test/*" ] +disable_error_code = ["return"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/scripts/generate_clients.sh b/scripts/generate_clients.sh index d588248..23c3e30 100755 --- a/scripts/generate_clients.sh +++ b/scripts/generate_clients.sh @@ -1,12 +1,14 @@ #!/bin/bash -SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" -SPEC_DIR="${SCRIPT_DIR}/../biosim_client/api_specs" -LIB_DIR="${SCRIPT_DIR}/../biosim_client/api_clients" +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd .. && pwd )" + +# make a clean ROOT_DIR without .. (hint, use dirname or something like that) +SPEC_DIR="${ROOT_DIR}/biosim_client/api_specs" +LIB_DIR="${ROOT_DIR}" +PACKAGE="biosim_client.simdata_api" # Generate simdata-api client -# TODO: need to customize the package name # TODO: improve Python typing for Mypy # TODO: make attributes dictionaries - easier to work with -openapi-generator generate -i ${SPEC_DIR}/simdata.json -g python -o ${LIB_DIR}/simdata +openapi-generator generate -i "${SPEC_DIR}/simdata.json" -g python -o "${LIB_DIR}" --additional-properties=packageName=${PACKAGE},generateSourceCodeOnly=true