index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
53,925
colorcet
get_aliases
Get the aliases for a given colormap name
def get_aliases(name): """Get the aliases for a given colormap name""" names = [name] def check_aliases(names, d, k_position=-1, v_position=0): for name in [n for n in names]: for k, v in d.items(): v = [v] if not isinstance(v, list) else v for vname in v: if name == vname and k not in names: if k_position == -2: names.append(k) else: names.insert(k_position, k) if name == k and vname not in names: if v_position == -2: names.append(vname) else: names.insert(v_position, vname) return names # Repeatedly look for new aliases until no new aliases are found n_names = len(names) while True: names = check_aliases(names, aliases, k_position=-2, v_position=0) names = check_aliases(names, cetnames_flipped, k_position=-2, v_position=-1) if len(names) == n_names: break n_names = len(names) # Sort names as 1or0_underscores, CET, multiple_under_scores (alias, cetname, algorithmicname) def name_sortfn(name): if name.count("_") > 1: return 2 if "CET" in name: return 1 return 0 return ', '.join(sorted(names, key=name_sortfn))
(name)
53,926
colorcet
mpl_cl
null
def mpl_cl(name,colorlist): cm[name] = ListedColormap(colorlist, name) register_cmap("cet_"+name, cmap=cm[name]) return cm[name]
(name, colorlist)
53,927
colorcet
mpl_cm
null
def mpl_cm(name,colorlist): cm[name] = LinearSegmentedColormap.from_list(name, colorlist, N=len(colorlist)) register_cmap("cet_"+name, cmap=cm[name]) return cm[name]
(name, colorlist)
53,928
colorcet
register_cmap
null
def register_cmap(name,cmap): pass
(name, cmap)
53,929
colorcet
rgb_to_hex
null
def rgb_to_hex(r,g,b): return '#%02x%02x%02x' % (r,g,b)
(r, g, b)
53,930
castxml
_program
null
def _program(name, args): return subprocess.call([os.path.join(BIN_DIR, name)] + args)
(name, args)
53,932
castxml
castxml
null
def castxml(): raise SystemExit(_program('castxml', sys.argv[1:]))
()
53,937
turbinia_api_lib.exceptions
ApiAttributeError
null
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)
(msg, path_to_item=None) -> None
53,938
turbinia_api_lib.exceptions
__init__
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
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)
(self, msg, path_to_item=None) -> NoneType
53,939
turbinia_api_lib.api_client
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 :param pool_threads: The number of threads to use for async requests to the API. More threads means more concurrent API requests.
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 :param pool_threads: The number of threads to use for async requests to the API. More threads means more concurrent API requests. """ PRIMITIVE_TYPES = (float, bool, bytes, 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, 'object': object, } _pool = None def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = '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): self.close() def close(self): if self._pool: self._pool.close() self._pool.join() self._pool = None if hasattr(atexit, 'unregister'): atexit.unregister(self.close) @property def pool(self): """Create thread pool on first request avoids instantiating unused threadpool for blocking clients. """ if self._pool is None: atexit.register(self.close) self._pool = ThreadPool(self.pool_threads) return self._pool @property def user_agent(self): """User agent for this API client""" return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value _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 __call_api( self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None): config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) path_params = self.parameters_to_tuples(path_params, collection_formats) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param) ) # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) post_params = self.parameters_to_tuples(post_params, collection_formats) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( header_params, query_params, auth_settings, resource_path, method, body, request_auth=_request_auth) # body if body: body = self.sanitize_for_serialization(body) # request url if _host is None: url = self.configuration.host + resource_path else: # use server/host defined in path or operation instead url = _host + resource_path # 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 try: # perform request and return response response_data = self.request( method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body, _preload_content=_preload_content, _request_timeout=_request_timeout) except ApiException as e: if e.body: e.body = e.body.decode('utf-8') raise e self.last_response = response_data return_data = None # assuming deserialization is not needed # data needs deserialization or returns HTTP data (deserialized) only if _preload_content or _return_http_data_only: 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) if response_type == "bytearray": response_data.data = response_data.data else: match = None content_type = response_data.getheader('content-type') if content_type is not None: match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) encoding = match.group(1) if match else "utf-8" response_data.data = response_data.data.decode(encoding) # deserialize response data if response_type == "bytearray": return_data = response_data.data elif response_type: return_data = self.deserialize(response_data, response_type) else: return_data = None if _return_http_data_only: return return_data else: 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 str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ if obj is None: return None elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except # attributes `openapi_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. obj_dict = obj.to_dict() return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()} def deserialize(self, response, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance if response_type == "file": return self.__deserialize_file(response) # fetch data from response object try: data = json.loads(response.data) except ValueError: data = response.data return self.__deserialize(data, response_type) def __deserialize(self, data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if isinstance(klass, str): if klass.startswith('List['): sub_kls = re.match(r'List\[(.*)]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: klass = getattr(turbinia_api_lib.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) else: return self.__deserialize_model(data, klass) def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, async_req=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None): """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async_req bool: execute request asynchronously :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :param collection_formats: dict of collection formats for path, query, header, and post parameters. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_token: dict, optional :return: If async_req parameter is True, the request will be called asynchronously. The method will return the request thread. If parameter async_req is False or missing, then the method will return the response directly. """ args = ( resource_path, method, path_params, query_params, header_params, body, post_params, files, response_types_map, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout, _host, _request_auth, ) if not async_req: return self.__call_api(*args) return self.pool.apply_async(self.__call_api, args) def request(self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.get_request(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.head_request(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.options_request(url, query_params=query_params, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout) elif method == "POST": return self.rest_client.post_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.put_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.patch_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.delete_request(url, query_params=query_params, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) else: raise ApiValueError( "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ new_params = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': new_params.extend((k, value) for value in v) else: if collection_format == 'ssv': delimiter = ' ' elif collection_format == 'tsv': delimiter = '\t' elif collection_format == 'pipes': delimiter = '|' else: # csv is the default delimiter = ',' new_params.append( (k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params def 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 = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 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=None): """Builds form parameters. :param files: File parameters. :return: Form parameters with files. """ params = [] if files: for k, v in files.items(): if not v: continue file_names = v if type(v) is list else [v] for n in file_names: with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream') params.append( tuple([k, tuple([filename, filedata, mimetype])])) return params def select_header_accept(self, accepts): """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: return 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): """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) return 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): """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. :param response: RESTResponse. :return: file path. """ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) os.close(fd) os.remove(path) content_disposition = response.getheader("Content-Disposition") if content_disposition: filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): """Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: return 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_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)
(configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> None
53,940
turbinia_api_lib.api_client
__call_api
null
def __call_api( self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None): config = self.configuration # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) header_params = dict(self.parameters_to_tuples(header_params, collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) path_params = self.parameters_to_tuples(path_params, collection_formats) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( '{%s}' % k, quote(str(v), safe=config.safe_chars_for_path_param) ) # post parameters if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) post_params = self.parameters_to_tuples(post_params, collection_formats) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( header_params, query_params, auth_settings, resource_path, method, body, request_auth=_request_auth) # body if body: body = self.sanitize_for_serialization(body) # request url if _host is None: url = self.configuration.host + resource_path else: # use server/host defined in path or operation instead url = _host + resource_path # 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 try: # perform request and return response response_data = self.request( method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body, _preload_content=_preload_content, _request_timeout=_request_timeout) except ApiException as e: if e.body: e.body = e.body.decode('utf-8') raise e self.last_response = response_data return_data = None # assuming deserialization is not needed # data needs deserialization or returns HTTP data (deserialized) only if _preload_content or _return_http_data_only: 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) if response_type == "bytearray": response_data.data = response_data.data else: match = None content_type = response_data.getheader('content-type') if content_type is not None: match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) encoding = match.group(1) if match else "utf-8" response_data.data = response_data.data.decode(encoding) # deserialize response data if response_type == "bytearray": return_data = response_data.data elif response_type: return_data = self.deserialize(response_data, response_type) else: return_data = None if _return_http_data_only: return return_data else: return ApiResponse(status_code = response_data.status, data = return_data, headers = response_data.getheaders(), raw_data = response_data.data)
(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None)
53,941
turbinia_api_lib.api_client
__deserialize
Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object.
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['): sub_kls = re.match(r'List\[(.*)]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: klass = self.NATIVE_TYPES_MAPPING[klass] else: klass = getattr(turbinia_api_lib.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) else: return self.__deserialize_model(data, klass)
(self, data, klass)
53,942
turbinia_api_lib.api_client
__deserialize_date
Deserializes string to date. :param string: str. :return: date.
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) )
(self, string)
53,943
turbinia_api_lib.api_client
__deserialize_datetime
Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime.
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) ) )
(self, string)
53,944
turbinia_api_lib.api_client
__deserialize_file
Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path.
def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) os.close(fd) os.remove(path) content_disposition = response.getheader("Content-Disposition") if content_disposition: filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: f.write(response.data) return path
(self, response)
53,945
turbinia_api_lib.api_client
__deserialize_model
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
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)
(self, data, klass)
53,946
turbinia_api_lib.api_client
__deserialize_object
Return an original value. :return: object.
def __deserialize_object(self, value): """Return an original value. :return: object. """ return value
(self, value)
53,947
turbinia_api_lib.api_client
__deserialize_primitive
Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool.
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
(self, data, klass)
53,949
turbinia_api_lib.api_client
__exit__
null
def __exit__(self, exc_type, exc_value, traceback): self.close()
(self, exc_type, exc_value, traceback)
53,950
turbinia_api_lib.api_client
__init__
null
def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. self.user_agent = 'OpenAPI-Generator/1.0.0/python' self.client_side_validation = configuration.client_side_validation
(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1) -> NoneType
53,951
turbinia_api_lib.api_client
_apply_auth_params
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
def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting): """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`' )
(self, headers, queries, resource_path, method, body, auth_setting)
53,952
turbinia_api_lib.api_client
call_api
Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async_req bool: execute request asynchronously :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :param collection_formats: dict of collection formats for path, query, header, and post parameters. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_token: dict, optional :return: If async_req parameter is True, the request will be called asynchronously. The method will return the request thread. If parameter async_req is False or missing, then the method will return the response directly.
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, async_req=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None): """Makes the HTTP request (synchronous) and returns deserialized data. To make an async_req request, set the async_req parameter. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param async_req bool: execute request asynchronously :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :param collection_formats: dict of collection formats for path, query, header, and post parameters. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_token: dict, optional :return: If async_req parameter is True, the request will be called asynchronously. The method will return the request thread. If parameter async_req is False or missing, then the method will return the response directly. """ args = ( resource_path, method, path_params, query_params, header_params, body, post_params, files, response_types_map, auth_settings, _return_http_data_only, collection_formats, _preload_content, _request_timeout, _host, _request_auth, ) if not async_req: return self.__call_api(*args) return self.pool.apply_async(self.__call_api, args)
(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_types_map=None, auth_settings=None, async_req=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None, _host=None, _request_auth=None)
53,953
turbinia_api_lib.api_client
close
null
def close(self): if self._pool: self._pool.close() self._pool.join() self._pool = None if hasattr(atexit, 'unregister'): atexit.unregister(self.close)
(self)
53,954
turbinia_api_lib.api_client
deserialize
Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :return: deserialized object.
def deserialize(self, response, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance if response_type == "file": return self.__deserialize_file(response) # fetch data from response object try: data = json.loads(response.data) except ValueError: data = response.data return self.__deserialize(data, response_type)
(self, response, response_type)
53,955
turbinia_api_lib.api_client
files_parameters
Builds form parameters. :param files: File parameters. :return: Form parameters with files.
def files_parameters(self, files=None): """Builds form parameters. :param files: File parameters. :return: Form parameters with files. """ params = [] if files: for k, v in files.items(): if not v: continue file_names = v if type(v) is list else [v] for n in file_names: with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = (mimetypes.guess_type(filename)[0] or 'application/octet-stream') params.append( tuple([k, tuple([filename, filedata, mimetype])])) return params
(self, files=None)
53,956
turbinia_api_lib.api_client
parameters_to_tuples
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
def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ new_params = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': new_params.extend((k, value) for value in v) else: if collection_format == 'ssv': delimiter = ' ' elif collection_format == 'tsv': delimiter = '\t' elif collection_format == 'pipes': delimiter = '|' else: # csv is the default delimiter = ',' new_params.append( (k, delimiter.join(str(value) for value in v))) else: new_params.append((k, v)) return new_params
(self, params, collection_formats)
53,957
turbinia_api_lib.api_client
parameters_to_url_query
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)
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 = [] if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 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])
(self, params, collection_formats)
53,958
turbinia_api_lib.api_client
request
Makes the HTTP request using RESTClient.
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None): """Makes the HTTP request using RESTClient.""" if method == "GET": return self.rest_client.get_request(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.head_request(url, query_params=query_params, _preload_content=_preload_content, _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.options_request(url, query_params=query_params, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout) elif method == "POST": return self.rest_client.post_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.put_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.patch_request(url, query_params=query_params, headers=headers, post_params=post_params, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.delete_request(url, query_params=query_params, headers=headers, _preload_content=_preload_content, _request_timeout=_request_timeout, body=body) else: raise ApiValueError( "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." )
(self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None)
53,959
turbinia_api_lib.api_client
sanitize_for_serialization
Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data.
def sanitize_for_serialization(self, obj): """Builds a JSON POST object. If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ if obj is None: return None elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except # attributes `openapi_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. obj_dict = obj.to_dict() return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()}
(self, obj)
53,960
turbinia_api_lib.api_client
select_header_accept
Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json).
def select_header_accept(self, accepts): """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: return for accept in accepts: if re.search('json', accept, re.IGNORECASE): return accept return accepts[0]
(self, accepts)
53,961
turbinia_api_lib.api_client
select_header_content_type
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).
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]
(self, content_types)
53,962
turbinia_api_lib.api_client
set_default_header
null
def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value
(self, header_name, header_value)
53,963
turbinia_api_lib.api_client
update_params_for_auth
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.
def update_params_for_auth(self, headers, queries, auth_settings, resource_path, method, body, request_auth=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) return 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)
(self, headers, queries, auth_settings, resource_path, method, body, request_auth=None)
53,964
turbinia_api_lib.exceptions
ApiException
null
class ApiException(OpenApiException): def __init__(self, status=None, reason=None, http_resp=None) -> None: if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: self.status = status self.reason = reason self.body = None self.headers = None 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.body: error_message += "HTTP response body: {0}\n".format(self.body) return error_message
(status=None, reason=None, http_resp=None) -> None
53,965
turbinia_api_lib.exceptions
__init__
null
def __init__(self, status=None, reason=None, http_resp=None) -> None: if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: self.status = status self.reason = reason self.body = None self.headers = None
(self, status=None, reason=None, http_resp=None) -> NoneType
53,966
turbinia_api_lib.exceptions
__str__
Custom error messages for exception
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.body: error_message += "HTTP response body: {0}\n".format(self.body) return error_message
(self)
53,967
turbinia_api_lib.exceptions
ApiKeyError
null
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)
(msg, path_to_item=None) -> None
53,968
turbinia_api_lib.exceptions
__init__
Args: msg (str): the exception message Keyword Args: path_to_item (None/list) the path to the exception in the received_data dict
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)
(self, msg, path_to_item=None) -> NoneType
53,969
turbinia_api_lib.api_response
ApiResponse
API response object
class ApiResponse: """ API response object """ status_code: Optional[StrictInt] = Field(None, description="HTTP status code") headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") data: Optional[Any] = Field(None, description="Deserialized data given the data type") raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") def __init__(self, status_code=None, headers=None, data=None, raw_data=None) -> None: self.status_code = status_code self.headers = headers self.data = data self.raw_data = raw_data
(status_code: Optional[pydantic.types.StrictInt] = None, headers: Optional[Dict[pydantic.types.StrictStr, pydantic.types.StrictStr]] = None, data: Optional[Any] = None, raw_data: Optional[Any] = None) -> 'None'
53,970
turbinia_api_lib.api_response
__init__
null
def __init__(self, status_code=None, headers=None, data=None, raw_data=None) -> None: self.status_code = status_code self.headers = headers self.data = data self.raw_data = raw_data
(self, status_code=None, headers=None, data=None, raw_data=None) -> NoneType
53,971
turbinia_api_lib.exceptions
ApiTypeError
null
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)
(msg, path_to_item=None, valid_classes=None, key_type=None) -> None
53,972
turbinia_api_lib.exceptions
__init__
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
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)
(self, msg, path_to_item=None, valid_classes=None, key_type=None) -> NoneType
53,973
turbinia_api_lib.exceptions
ApiValueError
null
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)
(msg, path_to_item=None) -> None
53,974
turbinia_api_lib.exceptions
__init__
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
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)
(self, msg, path_to_item=None) -> NoneType
53,975
turbinia_api_lib.models.base_request_options
BaseRequestOptions
Base Request Options class to be extended by other option types. # noqa: E501
class BaseRequestOptions(BaseModel): """ Base Request Options class to be extended by other option types. # noqa: E501 """ filter_patterns: Optional[conlist(StrictStr)] = None group_id: Optional[StrictStr] = None jobs_allowlist: Optional[conlist(StrictStr)] = None jobs_denylist: Optional[conlist(StrictStr)] = None reason: Optional[StrictStr] = None recipe_data: Optional[StrictStr] = None recipe_name: Optional[StrictStr] = None request_id: Optional[StrictStr] = None requester: Optional[StrictStr] = None sketch_id: Optional[StrictInt] = None yara_rules: Optional[StrictStr] = None __properties = ["filter_patterns", "group_id", "jobs_allowlist", "jobs_denylist", "reason", "recipe_data", "recipe_name", "request_id", "requester", "sketch_id", "yara_rules"] class Config: """Pydantic configuration""" allow_population_by_field_name = True validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> BaseRequestOptions: """Create an instance of BaseRequestOptions from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) return _dict @classmethod def from_dict(cls, obj: dict) -> BaseRequestOptions: """Create an instance of BaseRequestOptions from a dict""" if obj is None: return None if not isinstance(obj, dict): return BaseRequestOptions.parse_obj(obj) _obj = BaseRequestOptions.parse_obj({ "filter_patterns": obj.get("filter_patterns"), "group_id": obj.get("group_id"), "jobs_allowlist": obj.get("jobs_allowlist"), "jobs_denylist": obj.get("jobs_denylist"), "reason": obj.get("reason"), "recipe_data": obj.get("recipe_data"), "recipe_name": obj.get("recipe_name"), "request_id": obj.get("request_id"), "requester": obj.get("requester"), "sketch_id": obj.get("sketch_id"), "yara_rules": obj.get("yara_rules") }) return _obj
(*, filter_patterns: Optional[types.ConstrainedListValue] = None, group_id: Optional[pydantic.types.StrictStr] = None, jobs_allowlist: Optional[types.ConstrainedListValue] = None, jobs_denylist: Optional[types.ConstrainedListValue] = None, reason: Optional[pydantic.types.StrictStr] = None, recipe_data: Optional[pydantic.types.StrictStr] = None, recipe_name: Optional[pydantic.types.StrictStr] = None, request_id: Optional[pydantic.types.StrictStr] = None, requester: Optional[pydantic.types.StrictStr] = None, sketch_id: Optional[pydantic.types.StrictInt] = None, yara_rules: Optional[pydantic.types.StrictStr] = None) -> None
53,976
turbinia_api_lib.models.base_request_options
to_dict
Returns the dictionary representation of the model using alias
def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) return _dict
(self)
53,977
turbinia_api_lib.models.base_request_options
to_json
Returns the JSON representation of the model using alias
def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict())
(self) -> str
53,978
turbinia_api_lib.models.base_request_options
to_str
Returns the string representation of the model using alias
def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True))
(self) -> str
53,979
turbinia_api_lib.models.complete_turbinia_stats
CompleteTurbiniaStats
Statistics for different groups of tasks. # noqa: E501
class CompleteTurbiniaStats(BaseModel): """ Statistics for different groups of tasks. # noqa: E501 """ all_tasks: Optional[Dict[str, Any]] = None failed_tasks: Optional[Dict[str, Any]] = None requests: Optional[Dict[str, Any]] = None successful_tasks: Optional[Dict[str, Any]] = None tasks_per_type: Optional[Dict[str, Any]] = None tasks_per_user: Optional[Dict[str, Any]] = None tasks_per_worker: Optional[Dict[str, Any]] = None __properties = ["all_tasks", "failed_tasks", "requests", "successful_tasks", "tasks_per_type", "tasks_per_user", "tasks_per_worker"] class Config: """Pydantic configuration""" allow_population_by_field_name = True validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> CompleteTurbiniaStats: """Create an instance of CompleteTurbiniaStats from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) return _dict @classmethod def from_dict(cls, obj: dict) -> CompleteTurbiniaStats: """Create an instance of CompleteTurbiniaStats from a dict""" if obj is None: return None if not isinstance(obj, dict): return CompleteTurbiniaStats.parse_obj(obj) _obj = CompleteTurbiniaStats.parse_obj({ "all_tasks": obj.get("all_tasks"), "failed_tasks": obj.get("failed_tasks"), "requests": obj.get("requests"), "successful_tasks": obj.get("successful_tasks"), "tasks_per_type": obj.get("tasks_per_type"), "tasks_per_user": obj.get("tasks_per_user"), "tasks_per_worker": obj.get("tasks_per_worker") }) return _obj
(*, all_tasks: Optional[Dict[str, Any]] = None, failed_tasks: Optional[Dict[str, Any]] = None, requests: Optional[Dict[str, Any]] = None, successful_tasks: Optional[Dict[str, Any]] = None, tasks_per_type: Optional[Dict[str, Any]] = None, tasks_per_user: Optional[Dict[str, Any]] = None, tasks_per_worker: Optional[Dict[str, Any]] = None) -> None
53,983
turbinia_api_lib.configuration
Configuration
This class contains various settings of the API client. :param host: Base url. :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. :Example:
class Configuration: """This class contains various settings of the API client. :param host: Base url. :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. :Example: """ _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, ssl_ca_cert=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.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("turbinia_api_lib") 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 = None """Log file handler """ self.logger_file = None """Debug file location """ 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 = None """Proxy URL """ self.proxy_headers = None """Proxy headers """ self.safe_chars_for_path_param = '' """Safe chars for path_param """ self.retries = None """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 = {} if self.access_token is not None: auth['oAuth2'] = { 'type': 'oauth2', 'in': 'header', 'key': 'Authorization', 'value': 'Bearer ' + self.access_token } 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
(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, ssl_ca_cert=None) -> None
53,984
turbinia_api_lib.configuration
__deepcopy__
null
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
(self, memo)
53,985
turbinia_api_lib.configuration
__init__
Constructor
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, ssl_ca_cert=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.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("turbinia_api_lib") 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 = None """Log file handler """ self.logger_file = None """Debug file location """ 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 = None """Proxy URL """ self.proxy_headers = None """Proxy headers """ self.safe_chars_for_path_param = '' """Safe chars for path_param """ self.retries = None """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 """
(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, ssl_ca_cert=None) -> NoneType
53,986
turbinia_api_lib.configuration
__setattr__
null
def __setattr__(self, name, value): object.__setattr__(self, name, value)
(self, name, value)
53,987
turbinia_api_lib.configuration
auth_settings
Gets Auth Settings dict for api client. :return: The Auth Settings information dict.
def auth_settings(self): """Gets Auth Settings dict for api client. :return: The Auth Settings information dict. """ auth = {} if self.access_token is not None: auth['oAuth2'] = { 'type': 'oauth2', 'in': 'header', 'key': 'Authorization', 'value': 'Bearer ' + self.access_token } return auth
(self)
53,988
turbinia_api_lib.configuration
get_api_key_with_prefix
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.
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
(self, identifier, alias=None)
53,989
turbinia_api_lib.configuration
get_basic_auth_token
Gets HTTP basic authentication header (string). :return: The token for basic HTTP authentication.
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')
(self)
53,990
turbinia_api_lib.configuration
get_host_from_settings
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
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
(self, index, variables=None, servers=None)
53,991
turbinia_api_lib.configuration
get_host_settings
Gets an array of host settings :return: An array of host settings
def get_host_settings(self): """Gets an array of host settings :return: An array of host settings """ return [ { 'url': "", 'description': "No description provided", } ]
(self)
53,992
turbinia_api_lib.configuration
to_debug_report
Gets the essential information for debugging. :return: The report for debugging.
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)
(self)
53,993
turbinia_api_lib.models.http_validation_error
HTTPValidationError
HTTPValidationError
class HTTPValidationError(BaseModel): """ HTTPValidationError """ detail: Optional[conlist(ValidationError)] = None __properties = ["detail"] class Config: """Pydantic configuration""" allow_population_by_field_name = True validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> HTTPValidationError: """Create an instance of HTTPValidationError from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, 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 in self.detail: if _item: _items.append(_item.to_dict()) _dict['detail'] = _items return _dict @classmethod def from_dict(cls, obj: dict) -> HTTPValidationError: """Create an instance of HTTPValidationError from a dict""" if obj is None: return None if not isinstance(obj, dict): return HTTPValidationError.parse_obj(obj) _obj = HTTPValidationError.parse_obj({ "detail": [ValidationError.from_dict(_item) for _item in obj.get("detail")] if obj.get("detail") is not None else None }) return _obj
(*, detail: Optional[types.ConstrainedListValue] = None) -> None
53,994
turbinia_api_lib.models.http_validation_error
to_dict
Returns the dictionary representation of the model using alias
def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, 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 in self.detail: if _item: _items.append(_item.to_dict()) _dict['detail'] = _items return _dict
(self)
53,997
turbinia_api_lib.models.location_inner
LocationInner
LocationInner
class LocationInner(BaseModel): """ LocationInner """ # 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: Union[int, str] else: actual_instance: Any any_of_schemas: List[str] = Field(LOCATIONINNER_ANY_OF_SCHEMAS, const=True) class Config: validate_assignment = True 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) @validator('actual_instance') def actual_instance_must_validate_anyof(cls, v): instance = LocationInner.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 LocationInner with anyOf schemas: int, str. Details: " + ", ".join(error_messages)) else: return v @classmethod def from_dict(cls, obj: dict) -> LocationInner: return cls.from_json(json.dumps(obj)) @classmethod def from_json(cls, json_str: str) -> LocationInner: """Returns the object represented by the json string""" instance = LocationInner.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 LocationInner 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" to_json = getattr(self.actual_instance, "to_json", None) if callable(to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) def to_dict(self) -> dict: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return "null" to_json = getattr(self.actual_instance, "to_json", None) if callable(to_json): return self.actual_instance.to_dict() else: return json.dumps(self.actual_instance) def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.dict())
(*args, anyof_schema_1_validator: Optional[pydantic.types.StrictStr] = None, anyof_schema_2_validator: Optional[pydantic.types.StrictInt] = None, actual_instance: Any = None, any_of_schemas: List[str] = ['int', 'str']) -> None
53,998
turbinia_api_lib.models.location_inner
__init__
null
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)
(self, *args, **kwargs) -> NoneType
53,999
turbinia_api_lib.models.location_inner
to_dict
Returns the dict representation of the actual instance
def to_dict(self) -> dict: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return "null" to_json = getattr(self.actual_instance, "to_json", None) if callable(to_json): return self.actual_instance.to_dict() else: return json.dumps(self.actual_instance)
(self) -> dict
54,000
turbinia_api_lib.models.location_inner
to_json
Returns the JSON representation of the actual instance
def to_json(self) -> str: """Returns the JSON representation of the actual instance""" if self.actual_instance is None: return "null" to_json = getattr(self.actual_instance, "to_json", None) if callable(to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance)
(self) -> str
54,001
turbinia_api_lib.models.location_inner
to_str
Returns the string representation of the actual instance
def to_str(self) -> str: """Returns the string representation of the actual instance""" return pprint.pformat(self.dict())
(self) -> str
54,002
turbinia_api_lib.exceptions
OpenApiException
The base exception class for all OpenAPIExceptions
class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions"""
null
54,003
turbinia_api_lib.models.request
Request
Base request object. # noqa: E501
class Request(BaseModel): """ Base request object. # noqa: E501 """ description: Optional[StrictStr] = 'Turbinia request object' evidence: Dict[str, Any] = Field(...) request_options: BaseRequestOptions = Field(...) __properties = ["description", "evidence", "request_options"] class Config: """Pydantic configuration""" allow_population_by_field_name = True validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> Request: """Create an instance of Request from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of request_options if self.request_options: _dict['request_options'] = self.request_options.to_dict() return _dict @classmethod def from_dict(cls, obj: dict) -> Request: """Create an instance of Request from a dict""" if obj is None: return None if not isinstance(obj, dict): return Request.parse_obj(obj) _obj = Request.parse_obj({ "description": obj.get("description") if obj.get("description") is not None else 'Turbinia request object', "evidence": obj.get("evidence"), "request_options": BaseRequestOptions.from_dict(obj.get("request_options")) if obj.get("request_options") is not None else None }) return _obj
(*, description: Optional[pydantic.types.StrictStr] = 'Turbinia request object', evidence: Dict[str, Any], request_options: turbinia_api_lib.models.base_request_options.BaseRequestOptions) -> None
54,004
turbinia_api_lib.models.request
to_dict
Returns the dictionary representation of the model using alias
def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) # override the default output from pydantic by calling `to_dict()` of request_options if self.request_options: _dict['request_options'] = self.request_options.to_dict() return _dict
(self)
54,007
turbinia_api_lib.api.turbinia_configuration_api
TurbiniaConfigurationApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaConfigurationApi: """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_arguments def get_request_options(self, **kwargs) -> object: # noqa: E501 """Get Request Options # noqa: E501 Returns a list BaseRequestOptions attributes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_options(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_request_options_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_request_options_with_http_info(**kwargs) # noqa: E501 @validate_arguments def get_request_options_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 """Get Request Options # noqa: E501 Returns a list BaseRequestOptions attributes. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_options_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_request_options" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", } return self.api_client.call_api( '/api/config/request_options', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def read_config(self, **kwargs) -> object: # noqa: E501 """Read Config # noqa: E501 Retrieve turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_config(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the read_config_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.read_config_with_http_info(**kwargs) # noqa: E501 @validate_arguments def read_config_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 """Read Config # noqa: E501 Retrieve turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_config_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_config" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", } return self.api_client.call_api( '/api/config/', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,008
turbinia_api_lib.api.turbinia_configuration_api
__init__
null
def __init__(self, api_client=None) -> None: if api_client is None: api_client = ApiClient.get_default() self.api_client = api_client
(self, api_client=None) -> NoneType
54,009
turbinia_api_lib.api.turbinia_evidence_api
TurbiniaEvidenceApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaEvidenceApi: """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_arguments def get_evidence_attributes(self, evidence_type : Any, **kwargs) -> object: # noqa: E501 """Get Evidence Attributes # noqa: E501 Returns supported required parameters for evidence type. Args: evidence_type (str): Name of evidence type. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_attributes(evidence_type, async_req=True) >>> result = thread.get() :param evidence_type: (required) :type evidence_type: object :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_evidence_attributes_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_evidence_attributes_with_http_info(evidence_type, **kwargs) # noqa: E501 @validate_arguments def get_evidence_attributes_with_http_info(self, evidence_type : Any, **kwargs) -> ApiResponse: # noqa: E501 """Get Evidence Attributes # noqa: E501 Returns supported required parameters for evidence type. Args: evidence_type (str): Name of evidence type. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_attributes_with_http_info(evidence_type, async_req=True) >>> result = thread.get() :param evidence_type: (required) :type evidence_type: object :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'evidence_type' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_evidence_attributes" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['evidence_type'] is not None: _path_params['evidence_type'] = _params['evidence_type'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/evidence/types/{evidence_type}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_evidence_by_id(self, evidence_id : Any, **kwargs) -> object: # noqa: E501 """Get Evidence By Id # noqa: E501 Retrieves an evidence in Redis by using its UUID. Args: evidence_id (str): The UUID of the evidence. Raises: HTTPException: if the evidence is not found. Returns: Dictionary of the stored evidence # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_by_id(evidence_id, async_req=True) >>> result = thread.get() :param evidence_id: (required) :type evidence_id: object :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_evidence_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_evidence_by_id_with_http_info(evidence_id, **kwargs) # noqa: E501 @validate_arguments def get_evidence_by_id_with_http_info(self, evidence_id : Any, **kwargs) -> ApiResponse: # noqa: E501 """Get Evidence By Id # noqa: E501 Retrieves an evidence in Redis by using its UUID. Args: evidence_id (str): The UUID of the evidence. Raises: HTTPException: if the evidence is not found. Returns: Dictionary of the stored evidence # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_by_id_with_http_info(evidence_id, async_req=True) >>> result = thread.get() :param evidence_id: (required) :type evidence_id: object :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'evidence_id' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_evidence_by_id" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['evidence_id'] is not None: _path_params['evidence_id'] = _params['evidence_id'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/evidence/{evidence_id}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_evidence_summary(self, group : Optional[StrictStr] = None, output : Optional[StrictStr] = None, **kwargs) -> object: # noqa: E501 """Get Evidence Summary # noqa: E501 Retrieves a summary of all evidences in Redis. Args: group Optional(str): Attribute used to group summary. output Optional(str): Sets how the evidence found will be output. Returns: summary (dict): Summary of all evidences and their content. Raises: HTTPException: if there are no evidences. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_summary(group, output, async_req=True) >>> result = thread.get() :param group: :type group: str :param output: :type output: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_evidence_summary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_evidence_summary_with_http_info(group, output, **kwargs) # noqa: E501 @validate_arguments def get_evidence_summary_with_http_info(self, group : Optional[StrictStr] = None, output : Optional[StrictStr] = None, **kwargs) -> ApiResponse: # noqa: E501 """Get Evidence Summary # noqa: E501 Retrieves a summary of all evidences in Redis. Args: group Optional(str): Attribute used to group summary. output Optional(str): Sets how the evidence found will be output. Returns: summary (dict): Summary of all evidences and their content. Raises: HTTPException: if there are no evidences. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_summary_with_http_info(group, output, async_req=True) >>> result = thread.get() :param group: :type group: str :param output: :type output: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'group', 'output' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_evidence_summary" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] if _params.get('group') is not None: # noqa: E501 _query_params.append(('group', _params['group'])) if _params.get('output') is not None: # noqa: E501 _query_params.append(('output', _params['output'])) # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/evidence/summary', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_evidence_types(self, **kwargs) -> object: # noqa: E501 """Get Evidence Types # noqa: E501 Returns supported Evidence object types and required parameters. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_types(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_evidence_types_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_evidence_types_with_http_info(**kwargs) # noqa: E501 @validate_arguments def get_evidence_types_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 """Get Evidence Types # noqa: E501 Returns supported Evidence object types and required parameters. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_evidence_types_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_evidence_types" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", } return self.api_client.call_api( '/api/evidence/types', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def query_evidence(self, attribute_value : StrictStr, attribute_name : Optional[StrictStr] = None, output : Optional[StrictStr] = None, **kwargs) -> object: # noqa: E501 """Query Evidence # noqa: E501 Queries evidence in Redis that have the specified attribute value. Args: attribute_name (str): Name of attribute to be queried. attribute_value (str): Value the attribute must have. output Optional(str): Sets how the evidence found will be output. Returns: summary (dict): Summary of all evidences and their content. Raises: HTTPException: If no matching evidence is found. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.query_evidence(attribute_value, attribute_name, output, async_req=True) >>> result = thread.get() :param attribute_value: (required) :type attribute_value: str :param attribute_name: :type attribute_name: str :param output: :type output: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the query_evidence_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.query_evidence_with_http_info(attribute_value, attribute_name, output, **kwargs) # noqa: E501 @validate_arguments def query_evidence_with_http_info(self, attribute_value : StrictStr, attribute_name : Optional[StrictStr] = None, output : Optional[StrictStr] = None, **kwargs) -> ApiResponse: # noqa: E501 """Query Evidence # noqa: E501 Queries evidence in Redis that have the specified attribute value. Args: attribute_name (str): Name of attribute to be queried. attribute_value (str): Value the attribute must have. output Optional(str): Sets how the evidence found will be output. Returns: summary (dict): Summary of all evidences and their content. Raises: HTTPException: If no matching evidence is found. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.query_evidence_with_http_info(attribute_value, attribute_name, output, async_req=True) >>> result = thread.get() :param attribute_value: (required) :type attribute_value: str :param attribute_name: :type attribute_name: str :param output: :type output: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'attribute_value', 'attribute_name', 'output' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method query_evidence" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] if _params.get('attribute_name') is not None: # noqa: E501 _query_params.append(('attribute_name', _params['attribute_name'])) if _params.get('attribute_value') is not None: # noqa: E501 _query_params.append(('attribute_value', _params['attribute_value'])) if _params.get('output') is not None: # noqa: E501 _query_params.append(('output', _params['output'])) # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/evidence/query', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def upload_evidence(self, files : conlist(Union[StrictBytes, StrictStr]), ticket_id : StrictStr, calculate_hash : Optional[StrictBool] = None, **kwargs) -> object: # noqa: E501 """Upload Evidence # noqa: E501 Upload evidence file to server for processing. Args: ticket_id (str): ID of the ticket, which will be the name of the folder where the evidence will be saved. calculate_hash (bool): Boolean defining if the hash of the evidence should be calculated. file (List[UploadFile]): Evidence files to be uploaded to folder for later processing. The maximum size of the file is 10 GB. Returns: List of uploaded evidences or warning messages if any. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.upload_evidence(files, ticket_id, calculate_hash, async_req=True) >>> result = thread.get() :param files: (required) :type files: List[bytearray] :param ticket_id: (required) :type ticket_id: str :param calculate_hash: :type calculate_hash: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the upload_evidence_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.upload_evidence_with_http_info(files, ticket_id, calculate_hash, **kwargs) # noqa: E501 @validate_arguments def upload_evidence_with_http_info(self, files : conlist(Union[StrictBytes, StrictStr]), ticket_id : StrictStr, calculate_hash : Optional[StrictBool] = None, **kwargs) -> ApiResponse: # noqa: E501 """Upload Evidence # noqa: E501 Upload evidence file to server for processing. Args: ticket_id (str): ID of the ticket, which will be the name of the folder where the evidence will be saved. calculate_hash (bool): Boolean defining if the hash of the evidence should be calculated. file (List[UploadFile]): Evidence files to be uploaded to folder for later processing. The maximum size of the file is 10 GB. Returns: List of uploaded evidences or warning messages if any. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.upload_evidence_with_http_info(files, ticket_id, calculate_hash, async_req=True) >>> result = thread.get() :param files: (required) :type files: List[bytearray] :param ticket_id: (required) :type ticket_id: str :param calculate_hash: :type calculate_hash: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'files', 'ticket_id', 'calculate_hash' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method upload_evidence" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} if _params['calculate_hash'] is not None: _form_params.append(('calculate_hash', _params['calculate_hash'])) if _params['files'] is not None: _files['files'] = _params['files'] _collection_formats['files'] = 'csv' if _params['ticket_id'] is not None: _form_params.append(('ticket_id', _params['ticket_id'])) # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # set the HTTP header `Content-Type` _content_types_list = _params.get('_content_type', self.api_client.select_header_content_type( ['multipart/form-data'])) if _content_types_list: _header_params['Content-Type'] = _content_types_list # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/evidence/upload', 'POST', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,011
turbinia_api_lib.api.turbinia_jobs_api
TurbiniaJobsApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaJobsApi: """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_arguments def read_jobs(self, **kwargs) -> object: # noqa: E501 """Read Jobs # noqa: E501 Return enabled jobs from the current Turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_jobs(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the read_jobs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.read_jobs_with_http_info(**kwargs) # noqa: E501 @validate_arguments def read_jobs_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 """Read Jobs # noqa: E501 Return enabled jobs from the current Turbinia config. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_jobs_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method read_jobs" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", } return self.api_client.call_api( '/api/jobs/', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,013
turbinia_api_lib.api.turbinia_logs_api
TurbiniaLogsApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaLogsApi: """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_arguments def get_logs(self, query : StrictStr, **kwargs) -> object: # noqa: E501 """Get Logs # noqa: E501 Retrieve log data. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_logs(query, async_req=True) >>> result = thread.get() :param query: (required) :type query: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_logs_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_logs_with_http_info(query, **kwargs) # noqa: E501 @validate_arguments def get_logs_with_http_info(self, query : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 """Get Logs # noqa: E501 Retrieve log data. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_logs_with_http_info(query, async_req=True) >>> result = thread.get() :param query: (required) :type query: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'query' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_logs" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['query'] is not None: _path_params['query'] = _params['query'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/logs/{query}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,015
turbinia_api_lib.api.turbinia_request_results_api
TurbiniaRequestResultsApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaRequestResultsApi: """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_arguments def get_request_output(self, request_id : StrictStr, **kwargs) -> bytearray: # noqa: E501 """Get Request Output # noqa: E501 Retrieve request output. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_output(request_id, async_req=True) >>> result = thread.get() :param request_id: (required) :type request_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: bytearray """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_request_output_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_request_output_with_http_info(request_id, **kwargs) # noqa: E501 @validate_arguments def get_request_output_with_http_info(self, request_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 """Get Request Output # noqa: E501 Retrieve request output. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_output_with_http_info(request_id, async_req=True) >>> result = thread.get() :param request_id: (required) :type request_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'request_id' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_request_output" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['request_id'] is not None: _path_params['request_id'] = _params['request_id'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/octet-stream', 'application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "bytearray", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/result/request/{request_id}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_task_output(self, task_id : StrictStr, **kwargs) -> bytearray: # noqa: E501 """Get Task Output # noqa: E501 Retrieves a task's output files. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_output(task_id, async_req=True) >>> result = thread.get() :param task_id: (required) :type task_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: bytearray """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_task_output_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_task_output_with_http_info(task_id, **kwargs) # noqa: E501 @validate_arguments def get_task_output_with_http_info(self, task_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 """Get Task Output # noqa: E501 Retrieves a task's output files. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_output_with_http_info(task_id, async_req=True) >>> result = thread.get() :param task_id: (required) :type task_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'task_id' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_task_output" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['task_id'] is not None: _path_params['task_id'] = _params['task_id'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/octet-stream', 'application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "bytearray", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/result/task/{task_id}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,017
turbinia_api_lib.api.turbinia_requests_api
TurbiniaRequestsApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaRequestsApi: """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_arguments def create_request(self, request : Request, **kwargs) -> object: # noqa: E501 """Create Request # noqa: E501 Create a new Turbinia request. Args: request (Request): FastAPI request object. req (turbinia.api.schema.request): JSON object from the HTTP POST data matching the schema defined for a Turbinia Request. The schema is used by pydantic for field validation. Raises: ValidationError: if the Request object contains invalid data. HTTPException: If pre-conditions are not met. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_request(request, async_req=True) >>> result = thread.get() :param request: (required) :type request: Request :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the create_request_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.create_request_with_http_info(request, **kwargs) # noqa: E501 @validate_arguments def create_request_with_http_info(self, request : Request, **kwargs) -> ApiResponse: # noqa: E501 """Create Request # noqa: E501 Create a new Turbinia request. Args: request (Request): FastAPI request object. req (turbinia.api.schema.request): JSON object from the HTTP POST data matching the schema defined for a Turbinia Request. The schema is used by pydantic for field validation. Raises: ValidationError: if the Request object contains invalid data. HTTPException: If pre-conditions are not met. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_request_with_http_info(request, async_req=True) >>> result = thread.get() :param request: (required) :type request: Request :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'request' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method create_request" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None if _params['request'] is not None: _body_params = _params['request'] # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # set the HTTP header `Content-Type` _content_types_list = _params.get('_content_type', self.api_client.select_header_content_type( ['application/json'])) if _content_types_list: _header_params['Content-Type'] = _content_types_list # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/request/', 'POST', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_request_status(self, request_id : StrictStr, **kwargs) -> object: # noqa: E501 """Get Request Status # noqa: E501 Retrieves status for a Turbinia Request. Args: request (Request): FastAPI request object. request_id (str): A Turbinia request identifier. Raises: HTTPException: if another exception is caught. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_status(request_id, async_req=True) >>> result = thread.get() :param request_id: (required) :type request_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_request_status_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_request_status_with_http_info(request_id, **kwargs) # noqa: E501 @validate_arguments def get_request_status_with_http_info(self, request_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 """Get Request Status # noqa: E501 Retrieves status for a Turbinia Request. Args: request (Request): FastAPI request object. request_id (str): A Turbinia request identifier. Raises: HTTPException: if another exception is caught. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_request_status_with_http_info(request_id, async_req=True) >>> result = thread.get() :param request_id: (required) :type request_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'request_id' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_request_status" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['request_id'] is not None: _path_params['request_id'] = _params['request_id'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/request/{request_id}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_requests_summary(self, **kwargs) -> object: # noqa: E501 """Get Requests Summary # noqa: E501 Retrieves a summary of all Turbinia requests. The response is validated against the RequestSummary model. Raises: HTTPException: if another exception is caught. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_requests_summary(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_requests_summary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_requests_summary_with_http_info(**kwargs) # noqa: E501 @validate_arguments def get_requests_summary_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 """Get Requests Summary # noqa: E501 Retrieves a summary of all Turbinia requests. The response is validated against the RequestSummary model. Raises: HTTPException: if another exception is caught. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_requests_summary_with_http_info(async_req=True) >>> result = thread.get() :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_requests_summary" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", } return self.api_client.call_api( '/api/request/summary', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,019
turbinia_api_lib.api.turbinia_tasks_api
TurbiniaTasksApi
NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually.
class TurbiniaTasksApi: """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_arguments def get_task_statistics(self, days : Optional[StrictInt] = None, task_id : Optional[StrictStr] = None, request_id : Optional[StrictStr] = None, user : Optional[StrictStr] = None, **kwargs) -> CompleteTurbiniaStats: # noqa: E501 """Get Task Statistics # noqa: E501 Retrieves statistics for Turbinia execution. Args: days (int): The number of days we want history for. task_id (string): The Id of the task. request_id (string): The Id of the request we want tasks for. user (string): The user of the request we want tasks for. Returns: statistics (str): JSON-formatted task statistics report. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_statistics(days, task_id, request_id, user, async_req=True) >>> result = thread.get() :param days: :type days: int :param task_id: :type task_id: str :param request_id: :type request_id: str :param user: :type user: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: CompleteTurbiniaStats """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_task_statistics_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_task_statistics_with_http_info(days, task_id, request_id, user, **kwargs) # noqa: E501 @validate_arguments def get_task_statistics_with_http_info(self, days : Optional[StrictInt] = None, task_id : Optional[StrictStr] = None, request_id : Optional[StrictStr] = None, user : Optional[StrictStr] = None, **kwargs) -> ApiResponse: # noqa: E501 """Get Task Statistics # noqa: E501 Retrieves statistics for Turbinia execution. Args: days (int): The number of days we want history for. task_id (string): The Id of the task. request_id (string): The Id of the request we want tasks for. user (string): The user of the request we want tasks for. Returns: statistics (str): JSON-formatted task statistics report. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_statistics_with_http_info(days, task_id, request_id, user, async_req=True) >>> result = thread.get() :param days: :type days: int :param task_id: :type task_id: str :param request_id: :type request_id: str :param user: :type user: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(CompleteTurbiniaStats, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'days', 'task_id', 'request_id', 'user' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_task_statistics" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] if _params.get('days') is not None: # noqa: E501 _query_params.append(('days', _params['days'])) if _params.get('task_id') is not None: # noqa: E501 _query_params.append(('task_id', _params['task_id'])) if _params.get('request_id') is not None: # noqa: E501 _query_params.append(('request_id', _params['request_id'])) if _params.get('user') is not None: # noqa: E501 _query_params.append(('user', _params['user'])) # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "CompleteTurbiniaStats", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/task/statistics', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_task_status(self, task_id : StrictStr, **kwargs) -> object: # noqa: E501 """Get Task Status # noqa: E501 Retrieve task information. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_status(task_id, async_req=True) >>> result = thread.get() :param task_id: (required) :type task_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_task_status_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_task_status_with_http_info(task_id, **kwargs) # noqa: E501 @validate_arguments def get_task_status_with_http_info(self, task_id : StrictStr, **kwargs) -> ApiResponse: # noqa: E501 """Get Task Status # noqa: E501 Retrieve task information. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_task_status_with_http_info(task_id, async_req=True) >>> result = thread.get() :param task_id: (required) :type task_id: str :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'task_id' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_task_status" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} if _params['task_id'] is not None: _path_params['task_id'] = _params['task_id'] # process the query parameters _query_params = [] # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/task/{task_id}', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) @validate_arguments def get_workers_status(self, days : Optional[StrictInt] = None, all_fields : Optional[StrictBool] = None, **kwargs) -> object: # noqa: E501 """Get Workers Status # noqa: E501 Retrieves the workers status. Args: days (int): The UUID of the evidence. all_fields (bool): Returns all status fields if set to true. Returns: workers_status (str): JSON-formatted workers status. Raises: HTTPException: if no worker is found. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_workers_status(days, all_fields, async_req=True) >>> result = thread.get() :param days: :type days: int :param all_fields: :type all_fields: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: object """ kwargs['_return_http_data_only'] = True if '_preload_content' in kwargs: message = "Error! Please call the get_workers_status_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 raise ValueError(message) return self.get_workers_status_with_http_info(days, all_fields, **kwargs) # noqa: E501 @validate_arguments def get_workers_status_with_http_info(self, days : Optional[StrictInt] = None, all_fields : Optional[StrictBool] = None, **kwargs) -> ApiResponse: # noqa: E501 """Get Workers Status # noqa: E501 Retrieves the workers status. Args: days (int): The UUID of the evidence. all_fields (bool): Returns all status fields if set to true. Returns: workers_status (str): JSON-formatted workers status. Raises: HTTPException: if no worker is found. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_workers_status_with_http_info(days, all_fields, async_req=True) >>> result = thread.get() :param days: :type days: int :param all_fields: :type all_fields: bool :param async_req: Whether to execute the request asynchronously. :type async_req: bool, optional :param _preload_content: if False, the ApiResponse.data will be set to none and raw_data will store the HTTP response body without reading/decoding. Default is True. :type _preload_content: bool, optional :param _return_http_data_only: response data instead of ApiResponse object with status code, headers, etc :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :param _request_auth: set to override the auth_settings for an a single request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. :rtype: tuple(object, status_code(int), headers(HTTPHeaderDict)) """ _params = locals() _all_params = [ 'days', 'all_fields' ] _all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout', '_request_auth', '_content_type', '_headers' ] ) # validate the arguments for _key, _val in _params['kwargs'].items(): if _key not in _all_params: raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_workers_status" % _key ) _params[_key] = _val del _params['kwargs'] _collection_formats = {} # process the path parameters _path_params = {} # process the query parameters _query_params = [] if _params.get('days') is not None: # noqa: E501 _query_params.append(('days', _params['days'])) if _params.get('all_fields') is not None: # noqa: E501 _query_params.append(('all_fields', _params['all_fields'])) # process the header parameters _header_params = dict(_params.get('_headers', {})) # process the form parameters _form_params = [] _files = {} # process the body parameter _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # authentication setting _auth_settings = ['oAuth2'] # noqa: E501 _response_types_map = { '200': "object", '422': "HTTPValidationError", } return self.api_client.call_api( '/api/task/workers', 'GET', _path_params, _query_params, _header_params, body=_body_params, post_params=_form_params, files=_files, response_types_map=_response_types_map, auth_settings=_auth_settings, async_req=_params.get('async_req'), _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 _preload_content=_params.get('_preload_content', True), _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth'))
(api_client=None) -> None
54,021
turbinia_api_lib.models.validation_error
ValidationError
ValidationError
class ValidationError(BaseModel): """ ValidationError """ loc: conlist(LocationInner) = Field(...) msg: StrictStr = Field(...) type: StrictStr = Field(...) __properties = ["loc", "msg", "type"] class Config: """Pydantic configuration""" allow_population_by_field_name = True validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" return json.dumps(self.to_dict()) @classmethod def from_json(cls, json_str: str) -> ValidationError: """Create an instance of ValidationError from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, 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 in self.loc: if _item: _items.append(_item.to_dict()) _dict['loc'] = _items return _dict @classmethod def from_dict(cls, obj: dict) -> ValidationError: """Create an instance of ValidationError from a dict""" if obj is None: return None if not isinstance(obj, dict): return ValidationError.parse_obj(obj) _obj = ValidationError.parse_obj({ "loc": [LocationInner.from_dict(_item) for _item in obj.get("loc")] if obj.get("loc") is not None else None, "msg": obj.get("msg"), "type": obj.get("type") }) return _obj
(*, loc: types.ConstrainedListValue, msg: pydantic.types.StrictStr, type: pydantic.types.StrictStr) -> None
54,022
turbinia_api_lib.models.validation_error
to_dict
Returns the dictionary representation of the model using alias
def to_dict(self): """Returns the dictionary representation of the model using alias""" _dict = self.dict(by_alias=True, exclude={ }, 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 in self.loc: if _item: _items.append(_item.to_dict()) _dict['loc'] = _items return _dict
(self)
54,032
click_completion
DocumentedChoice
The choice type allows a value to be checked against a fixed set of supported values. All of these values have to be strings. Each value may be associated to a help message that will be display in the error message and during the completion. Parameters ---------- choices : dict or Enum A dictionary with the possible choice as key, and the corresponding help string as value
class DocumentedChoice(ParamType): """The choice type allows a value to be checked against a fixed set of supported values. All of these values have to be strings. Each value may be associated to a help message that will be display in the error message and during the completion. Parameters ---------- choices : dict or Enum A dictionary with the possible choice as key, and the corresponding help string as value """ name = 'choice' def __init__(self, choices): if isinstance(choices, Enum): self.choices = dict((choice.name, choice.value) for choice in choices) else: self.choices = dict(choices) def get_metavar(self, param): return '[%s]' % '|'.join(self.choices.keys()) def get_missing_message(self, param): formated_choices = ['{:<12} {}'.format(k, self.choices[k] or '') for k in sorted(self.choices.keys())] return 'Choose from\n ' + '\n '.join(formated_choices) def convert(self, value, param, ctx): # Exact match if value in self.choices: return value # Match through normalization if ctx is not None and \ ctx.token_normalize_func is not None: value = ctx.token_normalize_func(value) for choice in self.choices: if ctx.token_normalize_func(choice) == value: return choice self.fail('invalid choice: %s. %s' % (value, self.get_missing_message(param)), param, ctx) def __repr__(self): return 'DocumentedChoice(%r)' % list(self.choices.keys()) def complete(self, ctx, incomplete): match = completion_configuration.match_incomplete return [(c, v) for c, v in six.iteritems(self.choices) if match(c, incomplete)]
(choices)
54,034
click_completion
__init__
null
def __init__(self, choices): if isinstance(choices, Enum): self.choices = dict((choice.name, choice.value) for choice in choices) else: self.choices = dict(choices)
(self, choices)
54,035
click_completion
__repr__
null
def __repr__(self): return 'DocumentedChoice(%r)' % list(self.choices.keys())
(self)
54,036
click_completion
complete
null
def complete(self, ctx, incomplete): match = completion_configuration.match_incomplete return [(c, v) for c, v in six.iteritems(self.choices) if match(c, incomplete)]
(self, ctx, incomplete)
54,037
click_completion
convert
null
def convert(self, value, param, ctx): # Exact match if value in self.choices: return value # Match through normalization if ctx is not None and \ ctx.token_normalize_func is not None: value = ctx.token_normalize_func(value) for choice in self.choices: if ctx.token_normalize_func(choice) == value: return choice self.fail('invalid choice: %s. %s' % (value, self.get_missing_message(param)), param, ctx)
(self, value, param, ctx)
54,039
click_completion
get_metavar
null
def get_metavar(self, param): return '[%s]' % '|'.join(self.choices.keys())
(self, param)
54,040
click_completion
get_missing_message
null
def get_missing_message(self, param): formated_choices = ['{:<12} {}'.format(k, self.choices[k] or '') for k in sorted(self.choices.keys())] return 'Choose from\n ' + '\n '.join(formated_choices)
(self, param)
54,043
click.types
to_info_dict
Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0
def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] # Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type return {"param_type": param_type, "name": name}
(self) -> Dict[str, Any]
54,045
click.types
ParamType
Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input.
class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``None`` must return ``None``. This is already implemented by default. - :meth:`convert` must convert string values to the correct type. - :meth:`convert` must accept values that are already the correct type. - It must be able to convert a value if the ``ctx`` and ``param`` arguments are ``None``. This can occur when converting prompt input. """ is_composite: t.ClassVar[bool] = False arity: t.ClassVar[int] = 1 #: the descriptive name of this type name: str #: if a list of this type is expected and the value is pulled from a #: string environment variable, this is what splits it up. `None` #: means any whitespace. For all parameters the general rule is that #: whitespace splits them up. The exception are paths and files which #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on #: Windows). envvar_list_splitter: t.ClassVar[t.Optional[str]] = None def to_info_dict(self) -> t.Dict[str, t.Any]: """Gather information that could be useful for a tool generating user-facing documentation. Use :meth:`click.Context.to_info_dict` to traverse the entire CLI structure. .. versionadded:: 8.0 """ # The class name without the "ParamType" suffix. param_type = type(self).__name__.partition("ParamType")[0] param_type = param_type.partition("ParameterType")[0] # Custom subclasses might not remember to set a name. if hasattr(self, "name"): name = self.name else: name = param_type return {"param_type": param_type, "name": name} def __call__( self, value: t.Any, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> t.Any: if value is not None: return self.convert(value, param, ctx) def get_metavar(self, param: "Parameter") -> t.Optional[str]: """Returns the metavar default for this param if it provides one.""" def get_missing_message(self, param: "Parameter") -> t.Optional[str]: """Optionally might return extra information about a missing parameter. .. versionadded:: 2.0 """ def convert( self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"] ) -> t.Any: """Convert the value to the correct type. This is not called if the value is ``None`` (the missing value). This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types. The ``param`` and ``ctx`` arguments may be ``None`` in certain situations, such as when converting prompt input. If the value cannot be converted, call :meth:`fail` with a descriptive message. :param value: The value to convert. :param param: The parameter that is using this type to convert its value. May be ``None``. :param ctx: The current context that arrived at this value. May be ``None``. """ return value def split_envvar_value(self, rv: str) -> t.Sequence[str]: """Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter. If the splitter is set to `None`, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included. """ return (rv or "").split(self.envvar_list_splitter) def fail( self, message: str, param: t.Optional["Parameter"] = None, ctx: t.Optional["Context"] = None, ) -> "t.NoReturn": """Helper method to fail with an invalid value message.""" raise BadParameter(message, ctx=ctx, param=param) def shell_complete( self, ctx: "Context", param: "Parameter", incomplete: str ) -> t.List["CompletionItem"]: """Return a list of :class:`~click.shell_completion.CompletionItem` objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well. :param ctx: Invocation context for this command. :param param: The parameter that is requesting completion. :param incomplete: Value being completed. May be empty. .. versionadded:: 8.0 """ return []
()
54,054
click_completion.core
Shell
An enumeration.
class Shell(Enum): bash = 'Bourne again shell' fish = 'Friendly interactive shell' zsh = 'Z shell' powershell = 'Windows PowerShell'
(value, names=None, *, module=None, qualname=None, type=None, start=1)
54,055
click_completion.patch
patch
Patch click
def patch(): """Patch click""" import click click.types.ParamType.complete = param_type_complete click.types.Choice.complete = choice_complete click.core.MultiCommand.get_command_short_help = multicommand_get_command_short_help click.core.MultiCommand.get_command_hidden = multicommand_get_command_hidden click.core._bashcomplete = _shellcomplete
()
54,057
click_completion.lib
get_auto_shell
Returns the current shell
def get_auto_shell(): """Returns the current shell""" return shellingham.detect_shell()[0]
()
54,058
click_completion.core
get_choices
Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line args : [str] The arguments already written by the user on the command line incomplete : str The partial argument to complete Returns ------- [(str, str)] A list of completion results. The first element of each tuple is actually the argument to complete, the second element is an help string for this argument.
def get_choices(cli, prog_name, args, incomplete): """ Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line args : [str] The arguments already written by the user on the command line incomplete : str The partial argument to complete Returns ------- [(str, str)] A list of completion results. The first element of each tuple is actually the argument to complete, the second element is an help string for this argument. """ ctx = resolve_ctx(cli, prog_name, args) if ctx is None: return optctx = None if args: options = [param for param in ctx.command.get_params(ctx) if isinstance(param, Option)] arguments = [param for param in ctx.command.get_params(ctx) if isinstance(param, Argument)] for param in options: if not param.is_flag and args[-1] in param.opts + param.secondary_opts: optctx = param if optctx is None: for param in arguments: if ( not incomplete.startswith("-") and ( ctx.params.get(param.name) in (None, ()) or param.nargs == -1 ) ): optctx = param break choices = [] if optctx: choices += [c if isinstance(c, tuple) else (c, None) for c in optctx.type.complete(ctx, incomplete)] else: for param in ctx.command.get_params(ctx): if (completion_configuration.complete_options or incomplete and not incomplete[:1].isalnum()) and isinstance(param, Option): # filter hidden click.Option if getattr(param, 'hidden', False): continue for opt in param.opts: if match(opt, incomplete): choices.append((opt, param.help)) for opt in param.secondary_opts: if match(opt, incomplete): # don't put the doc so fish won't group the primary and # and secondary options choices.append((opt, None)) if isinstance(ctx.command, MultiCommand): for name in ctx.command.list_commands(ctx): if match(name, incomplete): choices.append((name, ctx.command.get_command_short_help(ctx, name))) for item, help in choices: yield (item, help)
(cli, prog_name, args, incomplete)
54,059
click_completion.core
get_code
Returns the completion code to be evaluated by the shell Parameters ---------- shell : Shell The shell type (Default value = None) prog_name : str The program name on the command line (Default value = None) env_name : str The environment variable used to control the completion (Default value = None) extra_env : dict Some extra environment variables to be added to the generated code (Default value = None) Returns ------- str The code to be evaluated by the shell
def get_code(shell=None, prog_name=None, env_name=None, extra_env=None): """Returns the completion code to be evaluated by the shell Parameters ---------- shell : Shell The shell type (Default value = None) prog_name : str The program name on the command line (Default value = None) env_name : str The environment variable used to control the completion (Default value = None) extra_env : dict Some extra environment variables to be added to the generated code (Default value = None) Returns ------- str The code to be evaluated by the shell """ from jinja2 import Environment, FileSystemLoader if shell in [None, 'auto']: shell = get_auto_shell() if not isinstance(shell, Shell): shell = Shell[shell] prog_name = prog_name or click.get_current_context().find_root().info_name env_name = env_name or '_%s_COMPLETE' % prog_name.upper().replace('-', '_') extra_env = extra_env if extra_env else {} env = Environment(loader=FileSystemLoader(os.path.dirname(__file__))) template = env.get_template('%s.j2' % shell.name) return template.render(prog_name=prog_name, complete_var=env_name, extra_env=extra_env)
(shell=None, prog_name=None, env_name=None, extra_env=None)
54,060
click_completion
init
Initialize the enhanced click completion Parameters ---------- complete_options : bool always complete the options, even when the user hasn't typed a first dash (Default value = False) match_incomplete : func a function with two parameters choice and incomplete. Must return True if incomplete is a correct match for choice, False otherwise.
def init(complete_options=False, match_incomplete=None): """Initialize the enhanced click completion Parameters ---------- complete_options : bool always complete the options, even when the user hasn't typed a first dash (Default value = False) match_incomplete : func a function with two parameters choice and incomplete. Must return True if incomplete is a correct match for choice, False otherwise. """ global _initialized if not _initialized: _patch() completion_configuration.complete_options = complete_options if match_incomplete is not None: completion_configuration.match_incomplete = match_incomplete _initialized = True
(complete_options=False, match_incomplete=None)
54,061
click_completion.core
install
Install the completion Parameters ---------- shell : Shell The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None) prog_name : str The program name on the command line. It will be automatically computed if the value is None (Default value = None) env_name : str The environment variable name used to control the completion. It will be automatically computed if the value is None (Default value = None) path : str The installation path of the code to be evaluated by the shell. The standard installation path is used if the value is None (Default value = None) append : bool Whether to append the content to the file or to override it. The default behavior depends on the shell type (Default value = None) extra_env : dict A set of environment variables and their values to be added to the generated code (Default value = None)
def install(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None): """Install the completion Parameters ---------- shell : Shell The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None) prog_name : str The program name on the command line. It will be automatically computed if the value is None (Default value = None) env_name : str The environment variable name used to control the completion. It will be automatically computed if the value is None (Default value = None) path : str The installation path of the code to be evaluated by the shell. The standard installation path is used if the value is None (Default value = None) append : bool Whether to append the content to the file or to override it. The default behavior depends on the shell type (Default value = None) extra_env : dict A set of environment variables and their values to be added to the generated code (Default value = None) """ prog_name = prog_name or click.get_current_context().find_root().info_name shell = shell or get_auto_shell() if append is None and path is not None: append = True if append is not None: mode = 'a' if append else 'w' else: mode = None if shell == 'fish': path = path or os.path.expanduser('~') + '/.config/fish/completions/%s.fish' % prog_name mode = mode or 'w' elif shell == 'bash': path = path or os.path.expanduser('~') + '/.bash_completion' mode = mode or 'a' elif shell == 'zsh': path = path or os.path.expanduser('~') + '/.zshrc' mode = mode or 'a' elif shell == 'powershell': subprocess.check_call(['powershell', 'Set-ExecutionPolicy Unrestricted -Scope CurrentUser']) path = path or subprocess.check_output(['powershell', '-NoProfile', 'echo $profile']).strip() if install else '' mode = mode or 'a' else: raise click.ClickException('%s is not supported.' % shell) if append is not None: mode = 'a' if append else 'w' else: mode = mode d = os.path.dirname(path) if not os.path.exists(d): os.makedirs(d) f = open(path, mode) f.write(get_code(shell, prog_name, env_name, extra_env)) f.write("\n") f.close() return shell, path
(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None)
54,064
click_completion.lib
resolve_ctx
Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line args : [str] The arguments already written by the user on the command line Returns ------- click.core.Context A new context corresponding to the current command
def resolve_ctx(cli, prog_name, args, resilient_parsing=True): """ Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line args : [str] The arguments already written by the user on the command line Returns ------- click.core.Context A new context corresponding to the current command """ ctx = cli.make_context(prog_name, list(args), resilient_parsing=resilient_parsing) while ctx.args + ctx.protected_args and isinstance(ctx.command, MultiCommand): a = ctx.protected_args + ctx.args cmd = ctx.command.get_command(ctx, a[0]) if cmd is None: return None if hasattr(cmd, "no_args_is_help"): no_args_is_help = cmd.no_args_is_help cmd.no_args_is_help = False ctx = cmd.make_context(a[0], a[1:], parent=ctx, resilient_parsing=resilient_parsing) if hasattr(cmd, "no_args_is_help"): cmd.no_args_is_help = no_args_is_help return ctx
(cli, prog_name, args, resilient_parsing=True)
54,066
click_completion.core
startswith
Returns True when string starts with incomplete It might be overridden with a fuzzier version - for example a case insensitive version Parameters ---------- string : str The string to check incomplete : str The incomplete string to compare to the begining of string Returns ------- bool True if string starts with incomplete, False otherwise
def startswith(string, incomplete): """Returns True when string starts with incomplete It might be overridden with a fuzzier version - for example a case insensitive version Parameters ---------- string : str The string to check incomplete : str The incomplete string to compare to the begining of string Returns ------- bool True if string starts with incomplete, False otherwise """ return string.startswith(incomplete)
(string, incomplete)
54,069
teradatasql
DBAPITypeObject
null
class DBAPITypeObject: def __init__(self, *values): self.values = values def __eq__(self, other): return other in self.values # end class DBAPITypeObject
(*values)
54,070
teradatasql
__eq__
null
def __eq__(self, other): return other in self.values
(self, other)
54,071
teradatasql
__init__
null
def __init__(self, *values): self.values = values
(self, *values)