pumpwood_communication.microservice_abc.parallel
Parallel Pumpwood microservice helpers.
Exports ABC mixins for parallel HTTP helpers. ParallelTaskErrorHandler,
ParallelErrorHandlerInput, ParallelErrorSentinel, and
partition_parallel_results support optional partial-failure handling on
ABCParallelBaseMicroservice.parallel_call.
1"""Parallel Pumpwood microservice helpers. 2 3Exports ABC mixins for parallel HTTP helpers. ``ParallelTaskErrorHandler``, 4``ParallelErrorHandlerInput``, ``ParallelErrorSentinel``, and 5``partition_parallel_results`` support optional partial-failure handling on 6``ABCParallelBaseMicroservice.parallel_call``. 7""" 8from .action import ABCParallelActionMicroservice 9from .delete import ABCParallelDeleteMicroservice 10from .list import ABCParallelListMicroservice 11from .retrieve import ABCParallelRetriveMicroservice 12from .save import ABCParallelSaveMicroservice 13from .batch import ABCParallelBatchMicroservice 14from .error_handler import ( 15 ParallelErrorSentinel, ParallelErrorHandlerInput, 16 ParallelTaskErrorHandler, 17 coerce_parallel_task_error_handler, is_parallel_error_sentinel, 18 partition_parallel_results) 19 20 21__docformat__ = "google" 22 23 24__all__ = [ 25 ABCParallelActionMicroservice, 26 ABCParallelDeleteMicroservice, 27 ABCParallelListMicroservice, 28 ABCParallelRetriveMicroservice, 29 ABCParallelSaveMicroservice, 30 ABCParallelBatchMicroservice, 31 ParallelErrorSentinel, 32 ParallelErrorHandlerInput, 33 ParallelTaskErrorHandler, 34 is_parallel_error_sentinel, 35 partition_parallel_results, 36 coerce_parallel_task_error_handler, 37]
10class ABCParallelActionMicroservice(ABCParallelBaseMicroservice): 11 """Abstract class for parallel calls at Pumpwood end-points.""" 12 13 def parallel_execute_action(self, model_class: Union[str, list[str]], 14 list_pk: list[int], 15 action: str | list[str], 16 parameters: dict | list[dict] = {}, 17 n_parallel: int = None, 18 auth_header: dict = None, 19 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 20 disable_etl_trigger: bool | list[bool] = False, 21 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 22 ) -> list[dict]: 23 """Make [n_parallel] parallel execute_action requests. 24 25 Args: 26 model_class: 27 Model Class to perform action over, 28 or a list of model class o make diferent actions. 29 list_pk: 30 A list of the pks to perform action or a 31 single pk to perform action with different paraemters. 32 action: 33 A list of actions to perform or a single 34 action to perform over all pks and parameters. 35 parameters: 36 Parameters used to perform actions 37 or a single dict to be used in all actions. 38 n_parallel: 39 Number of simultaneous requests. If not set, uses 40 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 41 (legacy spelling supported), default 4. 42 auth_header: 43 Auth header to substitute the microservice original 44 at the request (user impersonation). 45 base_filter_skip (list[str] | list[list[str]]): 46 List of base query filter to be skiped, it is necessary to 47 be superuser to skip base query filters. 48 disable_etl_trigger (bool): 49 Disable the ETL trigger for the object. 50 error_handler (ParallelErrorHandlerInput): 51 Forwarded to ``parallel_call``. 52 filter_errors (bool): 53 Forwarded to ``parallel_call``. Default ``True``. When 54 ``False``, return shape matches ``parallel_call``. 55 56 Returns: 57 list of the execute_action request data. 58 59 Raises: 60 PumpWoodException: 61 'parallel_length != len([argument])'. Indicates that function 62 arguments does not have all the same length. 63 64 Example: 65 No example yet. 66 """ 67 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 68 69 list_model_class = self.convert_to_list( 70 argument=model_class, length=len(list_pk)) 71 list_action = self.convert_to_list( 72 argument=action, length=len(list_pk)) 73 list_parameters = self.convert_to_list( 74 argument=parameters, length=len(list_pk)) 75 list_auth_header = self.convert_to_list( 76 argument=auth_header, length=len(list_pk)) 77 list_base_filter_skip = self.convert_to_list( 78 argument=base_filter_skip, length=len(list_pk), 79 force_replicate=True) 80 list_disable_etl_trigger = self.convert_to_list( 81 argument=disable_etl_trigger, length=len(list_pk)) 82 column_arg = { 83 'model_class': list_model_class, 84 'pk': list_pk, 85 'action': list_action, 86 'parameters': list_parameters, 87 'auth_header': list_auth_header, 88 'base_filter_skip': list_base_filter_skip, 89 'disable_etl_trigger': list_disable_etl_trigger, 90 } 91 92 function_args = self.transpose_args(dict_list=column_arg) 93 return self.parallel_call( 94 function=self.execute_action, function_args=function_args, 95 n_parallel=n_parallel, error_handler=error_handler, 96 filter_errors=filter_errors)
Abstract class for parallel calls at Pumpwood end-points.
13 def parallel_execute_action(self, model_class: Union[str, list[str]], 14 list_pk: list[int], 15 action: str | list[str], 16 parameters: dict | list[dict] = {}, 17 n_parallel: int = None, 18 auth_header: dict = None, 19 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 20 disable_etl_trigger: bool | list[bool] = False, 21 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 22 ) -> list[dict]: 23 """Make [n_parallel] parallel execute_action requests. 24 25 Args: 26 model_class: 27 Model Class to perform action over, 28 or a list of model class o make diferent actions. 29 list_pk: 30 A list of the pks to perform action or a 31 single pk to perform action with different paraemters. 32 action: 33 A list of actions to perform or a single 34 action to perform over all pks and parameters. 35 parameters: 36 Parameters used to perform actions 37 or a single dict to be used in all actions. 38 n_parallel: 39 Number of simultaneous requests. If not set, uses 40 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 41 (legacy spelling supported), default 4. 42 auth_header: 43 Auth header to substitute the microservice original 44 at the request (user impersonation). 45 base_filter_skip (list[str] | list[list[str]]): 46 List of base query filter to be skiped, it is necessary to 47 be superuser to skip base query filters. 48 disable_etl_trigger (bool): 49 Disable the ETL trigger for the object. 50 error_handler (ParallelErrorHandlerInput): 51 Forwarded to ``parallel_call``. 52 filter_errors (bool): 53 Forwarded to ``parallel_call``. Default ``True``. When 54 ``False``, return shape matches ``parallel_call``. 55 56 Returns: 57 list of the execute_action request data. 58 59 Raises: 60 PumpWoodException: 61 'parallel_length != len([argument])'. Indicates that function 62 arguments does not have all the same length. 63 64 Example: 65 No example yet. 66 """ 67 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 68 69 list_model_class = self.convert_to_list( 70 argument=model_class, length=len(list_pk)) 71 list_action = self.convert_to_list( 72 argument=action, length=len(list_pk)) 73 list_parameters = self.convert_to_list( 74 argument=parameters, length=len(list_pk)) 75 list_auth_header = self.convert_to_list( 76 argument=auth_header, length=len(list_pk)) 77 list_base_filter_skip = self.convert_to_list( 78 argument=base_filter_skip, length=len(list_pk), 79 force_replicate=True) 80 list_disable_etl_trigger = self.convert_to_list( 81 argument=disable_etl_trigger, length=len(list_pk)) 82 column_arg = { 83 'model_class': list_model_class, 84 'pk': list_pk, 85 'action': list_action, 86 'parameters': list_parameters, 87 'auth_header': list_auth_header, 88 'base_filter_skip': list_base_filter_skip, 89 'disable_etl_trigger': list_disable_etl_trigger, 90 } 91 92 function_args = self.transpose_args(dict_list=column_arg) 93 return self.parallel_call( 94 function=self.execute_action, function_args=function_args, 95 n_parallel=n_parallel, error_handler=error_handler, 96 filter_errors=filter_errors)
Make [n_parallel] parallel execute_action requests.
Arguments:
- model_class: Model Class to perform action over, or a list of model class o make diferent actions.
- list_pk: A list of the pks to perform action or a single pk to perform action with different paraemters.
- action: A list of actions to perform or a single action to perform over all pks and parameters.
- parameters: Parameters used to perform actions or a single dict to be used in all actions.
- n_parallel: Number of simultaneous requests. If not set, uses
PUMPWOOD_COMMUNICATION__N_PARALLELenv variable (legacy spelling supported), default 4. - auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list[str] | list[list[str]]): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- disable_etl_trigger (bool): Disable the ETL trigger for the object.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
list of the execute_action request data.
Raises:
- PumpWoodException: 'parallel_length != len([argument])'. Indicates that function arguments does not have all the same length.
Example:
No example yet.
10class ABCParallelDeleteMicroservice(ABCParallelBaseMicroservice): 11 """Abstract class for parallel calls at Pumpwood end-points.""" 12 13 def parallel_delete(self, model_class: Union[str, list[str]], 14 list_pk: list[int], n_parallel: int = None, 15 auth_header: dict = None, 16 base_filter_skip: list[str] | list[list[str]] = None, 17 disable_etl_trigger: bool | list[bool] = False, 18 error_handler: ParallelErrorHandlerInput = 19 None, filter_errors: bool = True): 20 """Make many [n_parallel] delete requests. 21 22 Args: 23 model_class: 24 Model Class to list one. 25 list_pk: 26 List of the pks to list one. 27 n_parallel: 28 Number of simultaneous requests. If not set, uses 29 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 30 (legacy spelling supported), default 4. 31 auth_header: 32 Auth header to substitute the microservice original 33 at the request (user impersonation). 34 base_filter_skip (list): 35 List of base query filter to be skiped, it is necessary to 36 be superuser to skip base query filters. 37 disable_etl_trigger (bool): 38 Disable the ETL trigger for the object. 39 error_handler (ParallelErrorHandlerInput): 40 Forwarded to ``parallel_call``. 41 filter_errors (bool): 42 Forwarded to ``parallel_call``. Default ``True``. When 43 ``False``, return shape matches ``parallel_call``. 44 45 Returns: 46 List of the delete request data. 47 48 Raises: 49 PumpWoodException: 50 'len(model_class)[{}] != len(list_args)[{}]'. Indicates 51 that length of model_class and list_args arguments are not 52 equal. 53 """ 54 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 55 56 list_model_class = self.convert_to_list( 57 argument=model_class, length=len(list_pk)) 58 list_auth_header = self.convert_to_list( 59 argument=auth_header, length=len(list_pk)) 60 list_base_filter_skip = self.convert_to_list( 61 argument=base_filter_skip, length=len(list_pk), 62 force_replicate=True) 63 list_disable_etl_trigger = self.convert_to_list( 64 argument=disable_etl_trigger, length=len(list_pk)) 65 column_arg = { 66 'model_class': list_model_class, 67 'auth_header': list_auth_header, 68 'base_filter_skip': list_base_filter_skip, 69 'pk': list_pk, 70 'disable_etl_trigger': list_disable_etl_trigger, 71 } 72 73 function_args = self.transpose_args(dict_list=column_arg) 74 return self.parallel_call( 75 function=self.delete, function_args=function_args, 76 n_parallel=n_parallel, error_handler=error_handler, 77 filter_errors=filter_errors) 78 79 def parallel_delete_many(self, model_class: Union[str, List[str]], 80 list_args: List[dict], n_parallel: int = None, 81 auth_header: dict = None, 82 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 83 error_handler: ParallelErrorHandlerInput = 84 None, filter_errors: bool = True 85 ) -> List[dict]: 86 """Make [n_parallel] parallel delete_many request. 87 88 Args: 89 model_class (str): 90 Model Class to delete many. 91 list_args (list): 92 A list of list request args (filter_dict, exclude_dict). 93 n_parallel: 94 Number of simultaneous requests. If not set, uses 95 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 96 (legacy spelling supported), default 4. 97 auth_header: 98 Auth header to substitute the microservice original 99 at the request (user impersonation). 100 base_filter_skip (list): 101 List of base query filter to be skiped, it is necessary to 102 be superuser to skip base query filters. 103 error_handler (ParallelErrorHandlerInput): 104 Forwarded to ``parallel_call``. 105 filter_errors (bool): 106 Forwarded to ``parallel_call``. Default ``True``. When 107 ``False``, return shape matches ``parallel_call``. 108 109 Returns: 110 List of the delete many request reponses. 111 112 Raises: 113 PumpWoodException: 114 'len(model_class)[{}] != len(list_args)[{}]'. Indicates 115 that length of model_class and list_args arguments 116 are not equal. 117 118 Example: 119 No example yet. 120 """ 121 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 122 123 dict_list = self.expand_list_args( 124 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 125 list_model_class = self.convert_to_list( 126 argument=model_class, length=len(list_args)) 127 list_auth_header = self.convert_to_list( 128 argument=auth_header, length=len(list_args)) 129 list_base_filter_skip = self.convert_to_list( 130 argument=base_filter_skip, length=len(list_args), 131 force_replicate=True) 132 column_arg = { 133 'model_class': list_model_class, 134 'auth_header': list_auth_header, 135 'base_filter_skip': list_base_filter_skip} 136 column_arg.update(dict_list) 137 138 function_args = self.transpose_args(dict_list=column_arg) 139 return self.parallel_call( 140 function=self.delete_many, function_args=function_args, 141 n_parallel=n_parallel, error_handler=error_handler, 142 filter_errors=filter_errors)
Abstract class for parallel calls at Pumpwood end-points.
13 def parallel_delete(self, model_class: Union[str, list[str]], 14 list_pk: list[int], n_parallel: int = None, 15 auth_header: dict = None, 16 base_filter_skip: list[str] | list[list[str]] = None, 17 disable_etl_trigger: bool | list[bool] = False, 18 error_handler: ParallelErrorHandlerInput = 19 None, filter_errors: bool = True): 20 """Make many [n_parallel] delete requests. 21 22 Args: 23 model_class: 24 Model Class to list one. 25 list_pk: 26 List of the pks to list one. 27 n_parallel: 28 Number of simultaneous requests. If not set, uses 29 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 30 (legacy spelling supported), default 4. 31 auth_header: 32 Auth header to substitute the microservice original 33 at the request (user impersonation). 34 base_filter_skip (list): 35 List of base query filter to be skiped, it is necessary to 36 be superuser to skip base query filters. 37 disable_etl_trigger (bool): 38 Disable the ETL trigger for the object. 39 error_handler (ParallelErrorHandlerInput): 40 Forwarded to ``parallel_call``. 41 filter_errors (bool): 42 Forwarded to ``parallel_call``. Default ``True``. When 43 ``False``, return shape matches ``parallel_call``. 44 45 Returns: 46 List of the delete request data. 47 48 Raises: 49 PumpWoodException: 50 'len(model_class)[{}] != len(list_args)[{}]'. Indicates 51 that length of model_class and list_args arguments are not 52 equal. 53 """ 54 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 55 56 list_model_class = self.convert_to_list( 57 argument=model_class, length=len(list_pk)) 58 list_auth_header = self.convert_to_list( 59 argument=auth_header, length=len(list_pk)) 60 list_base_filter_skip = self.convert_to_list( 61 argument=base_filter_skip, length=len(list_pk), 62 force_replicate=True) 63 list_disable_etl_trigger = self.convert_to_list( 64 argument=disable_etl_trigger, length=len(list_pk)) 65 column_arg = { 66 'model_class': list_model_class, 67 'auth_header': list_auth_header, 68 'base_filter_skip': list_base_filter_skip, 69 'pk': list_pk, 70 'disable_etl_trigger': list_disable_etl_trigger, 71 } 72 73 function_args = self.transpose_args(dict_list=column_arg) 74 return self.parallel_call( 75 function=self.delete, function_args=function_args, 76 n_parallel=n_parallel, error_handler=error_handler, 77 filter_errors=filter_errors)
Make many [n_parallel] delete requests.
Arguments:
- model_class: Model Class to list one.
- list_pk: List of the pks to list one.
- n_parallel: Number of simultaneous requests. If not set, uses
PUMPWOOD_COMMUNICATION__N_PARALLELenv variable (legacy spelling supported), default 4. - auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- disable_etl_trigger (bool): Disable the ETL trigger for the object.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
List of the delete request data.
Raises:
- PumpWoodException: 'len(model_class)[{}] != len(list_args)[{}]'. Indicates that length of model_class and list_args arguments are not equal.
79 def parallel_delete_many(self, model_class: Union[str, List[str]], 80 list_args: List[dict], n_parallel: int = None, 81 auth_header: dict = None, 82 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 83 error_handler: ParallelErrorHandlerInput = 84 None, filter_errors: bool = True 85 ) -> List[dict]: 86 """Make [n_parallel] parallel delete_many request. 87 88 Args: 89 model_class (str): 90 Model Class to delete many. 91 list_args (list): 92 A list of list request args (filter_dict, exclude_dict). 93 n_parallel: 94 Number of simultaneous requests. If not set, uses 95 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 96 (legacy spelling supported), default 4. 97 auth_header: 98 Auth header to substitute the microservice original 99 at the request (user impersonation). 100 base_filter_skip (list): 101 List of base query filter to be skiped, it is necessary to 102 be superuser to skip base query filters. 103 error_handler (ParallelErrorHandlerInput): 104 Forwarded to ``parallel_call``. 105 filter_errors (bool): 106 Forwarded to ``parallel_call``. Default ``True``. When 107 ``False``, return shape matches ``parallel_call``. 108 109 Returns: 110 List of the delete many request reponses. 111 112 Raises: 113 PumpWoodException: 114 'len(model_class)[{}] != len(list_args)[{}]'. Indicates 115 that length of model_class and list_args arguments 116 are not equal. 117 118 Example: 119 No example yet. 120 """ 121 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 122 123 dict_list = self.expand_list_args( 124 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 125 list_model_class = self.convert_to_list( 126 argument=model_class, length=len(list_args)) 127 list_auth_header = self.convert_to_list( 128 argument=auth_header, length=len(list_args)) 129 list_base_filter_skip = self.convert_to_list( 130 argument=base_filter_skip, length=len(list_args), 131 force_replicate=True) 132 column_arg = { 133 'model_class': list_model_class, 134 'auth_header': list_auth_header, 135 'base_filter_skip': list_base_filter_skip} 136 column_arg.update(dict_list) 137 138 function_args = self.transpose_args(dict_list=column_arg) 139 return self.parallel_call( 140 function=self.delete_many, function_args=function_args, 141 n_parallel=n_parallel, error_handler=error_handler, 142 filter_errors=filter_errors)
Make [n_parallel] parallel delete_many request.
Arguments:
- model_class (str): Model Class to delete many.
- list_args (list): A list of list request args (filter_dict, exclude_dict).
- n_parallel: Number of simultaneous requests. If not set, uses
PUMPWOOD_COMMUNICATION__N_PARALLELenv variable (legacy spelling supported), default 4. - auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
List of the delete many request reponses.
Raises:
- PumpWoodException: 'len(model_class)[{}] != len(list_args)[{}]'. Indicates that length of model_class and list_args arguments are not equal.
Example:
No example yet.
10class ABCParallelListMicroservice(ABCParallelBaseMicroservice): 11 """Abstract class for parallel calls at Pumpwood end-points.""" 12 13 def parallel_list(self, model_class: Union[str, List[str]], 14 list_args: List[dict], 15 auth_header: dict = None, fields: list = None, 16 default_fields: bool = False, limit: int = None, 17 foreign_key_fields: bool = False, 18 base_filter_skip: list = None, 19 n_parallel: int = None, 20 flat_results: bool = True, 21 as_dataframe: bool = False, 22 error_handler: ParallelErrorHandlerInput = None, 23 filter_errors: bool = True) -> List[dict]: 24 """List objects with pagination. 25 26 Args: 27 model_class: 28 Model class of the end-point 29 list_args: 30 filter_dict: 31 Filter dict to be used at the query. Filter elements from 32 query return that satifies all statements of the dictonary. 33 exclude_dict: 34 Exclude dict to be used at the query. Remove elements from 35 query return that satifies all statements of the dictonary. 36 order_by: Order results acording to list of strings 37 correspondent to fields. It is possible to use '-' at the 38 begginng of the field name for reverse ordering. Ex.: 39 ['description'] for accendent ordering and ['-description'] 40 for descendent ordering. 41 auth_header: 42 Auth header to substitute the microservice original 43 at the request (user impersonation). 44 fields (list): 45 Set the fields to be returned by the list end-point. 46 default_fields (bool): 47 Boolean, if true and fields arguments None will return the 48 default fields set for list by the backend. 49 limit (int): 50 Set the limit of elements of the returned query. By default, 51 backend usually return 50 elements. 52 foreign_key_fields (bool): 53 Return forenging key objects. It will return the fk 54 corresponding object. Ex: `created_by_id` reference to 55 a user `model_class` the correspondent to User will be 56 returned at `created_by`. 57 base_filter_skip (list): 58 List of base query filter to be skiped, it is necessary to 59 be superuser to skip base query filters. 60 n_parallel (int): 61 Number of parallel requests, if None will use the default 62 one. 63 flat_results (bool): 64 The results will be joined on a single list. 65 as_dataframe (bool): 66 If True, returns the results as a pandas DataFrame. 67 error_handler (ParallelErrorHandlerInput): 68 Forwarded to ``parallel_call``. 69 filter_errors (bool): 70 Forwarded to ``parallel_call``. Default ``True``. When 71 ``False``, return shape matches ``parallel_call``. 72 73 Returns: 74 Containing objects serialized by list Serializer. 75 76 Raises: 77 No especific raises. 78 """ # NOQA 79 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 80 81 # Convert arguments to list 82 dict_list = self.expand_list_args(list_args=list_args) 83 list_model_class = self.convert_to_list( 84 argument=model_class, length=len(list_args)) 85 list_auth_header = self.convert_to_list( 86 argument=auth_header, length=len(list_args)) 87 list_fields = self.convert_to_list( 88 argument=fields, length=len(list_args), 89 force_replicate=True) 90 list_default_fields = self.convert_to_list( 91 argument=default_fields, length=len(list_args)) 92 list_limit = self.convert_to_list( 93 argument=limit, length=len(list_args)) 94 list_foreign_key_fields = self.convert_to_list( 95 argument=foreign_key_fields, length=len(list_args)) 96 list_base_filter_skip = self.convert_to_list( 97 argument=base_filter_skip, length=len(list_args), 98 force_replicate=True) 99 list_as_dataframe = self.convert_to_list( 100 argument=as_dataframe, length=len(list_args), 101 force_replicate=True) 102 103 column_arg = { 104 'model_class': list_model_class, 105 'auth_header': list_auth_header, 106 'fields': list_fields, 107 'default_fields': list_default_fields, 108 'limit': list_limit, 109 'foreign_key_fields': list_foreign_key_fields, 110 'base_filter_skip': list_base_filter_skip, 111 "as_dataframe": list_as_dataframe 112 } 113 column_arg.update(dict_list) 114 115 function_args = self.transpose_args(dict_list=column_arg) 116 parallel_results = self.parallel_call( 117 function=self.list, function_args=function_args, 118 n_parallel=n_parallel, error_handler=error_handler, 119 filter_errors=filter_errors) 120 return self.finalize_parallel_output( 121 parallel_results, flat_results=flat_results) 122 123 def parallel_list_without_pag(self, model_class: Union[str, List[str]], 124 list_args: List[dict], 125 auth_header: dict = None, 126 fields: list = None, 127 default_fields: bool = False, 128 foreign_key_fields: bool = False, 129 base_filter_skip: list = None, 130 n_parallel: int = None, 131 flat_results: bool = True, 132 as_dataframe: bool = False, 133 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 134 ) -> List[dict]: 135 """List objects with pagination. 136 137 Args: 138 model_class: 139 Model class of the end-point 140 list_args: 141 filter_dict: 142 Filter dict to be used at the query. Filter elements from 143 query return that satifies all statements of the dictonary. 144 exclude_dict: 145 Exclude dict to be used at the query. Remove elements from 146 query return that satifies all statements of the dictonary. 147 auth_header: 148 Auth header to substitute the microservice original 149 at the request (user impersonation). 150 fields (list): 151 Set the fields to be returned by the list end-point. 152 default_fields (bool): 153 Boolean, if true and fields arguments None will return the 154 default fields set for list by the backend. 155 foreign_key_fields (bool): 156 Return forenging key objects. It will return the fk 157 corresponding object. Ex: `created_by_id` reference to 158 a user `model_class` the correspondent to User will be 159 returned at `created_by`. 160 base_filter_skip (list): 161 List of base query filter to be skiped, it is necessary to 162 be superuser to skip base query filters. 163 n_parallel (int): 164 Number of parallel requests, if None will use the default 165 one. 166 flat_results (bool): 167 The results will be joined on a single list. 168 as_dataframe (bool): 169 If True, returns the results as a pandas DataFrame. 170 error_handler (ParallelErrorHandlerInput): 171 Forwarded to ``parallel_call``. 172 filter_errors (bool): 173 Forwarded to ``parallel_call``. Default ``True``. When 174 ``False``, return shape matches ``parallel_call``. 175 176 Returns: 177 Containing objects serialized by list Serializer. 178 179 Raises: 180 No especific raises. 181 """ # NOQA 182 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 183 184 # Convert arguments to list 185 dict_list = self.expand_list_args( 186 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 187 list_model_class = self.convert_to_list( 188 argument=model_class, length=len(list_args)) 189 list_auth_header = self.convert_to_list( 190 argument=auth_header, length=len(list_args)) 191 list_fields = self.convert_to_list( 192 argument=fields, length=len(list_args), 193 force_replicate=True) 194 list_default_fields = self.convert_to_list( 195 argument=default_fields, length=len(list_args)) 196 list_foreign_key_fields = self.convert_to_list( 197 argument=foreign_key_fields, length=len(list_args)) 198 list_base_filter_skip = self.convert_to_list( 199 argument=base_filter_skip, length=len(list_args), 200 force_replicate=True) 201 list_as_dataframe = self.convert_to_list( 202 argument=as_dataframe, length=len(list_args), 203 force_replicate=True) 204 205 column_arg = { 206 'model_class': list_model_class, 207 'auth_header': list_auth_header, 208 'fields': list_fields, 209 'default_fields': list_default_fields, 210 'foreign_key_fields': list_foreign_key_fields, 211 'base_filter_skip': list_base_filter_skip, 212 "as_dataframe": list_as_dataframe 213 } 214 column_arg.update(dict_list) 215 216 function_args = self.transpose_args(dict_list=column_arg) 217 parallel_results = self.parallel_call( 218 function=self.list_without_pag, function_args=function_args, 219 n_parallel=n_parallel, error_handler=error_handler, 220 filter_errors=filter_errors) 221 return self.finalize_parallel_output( 222 parallel_results, flat_results=flat_results, 223 as_dataframe=as_dataframe) 224 225 def parallel_list_by_chunks(self, model_class: Union[str, List[str]], 226 list_args: List[dict], 227 auth_header: dict = None, 228 fields: list = None, 229 default_fields: bool = False, 230 base_filter_skip: list = None, 231 n_parallel: int = None, 232 chunk_size: int = 50000, 233 foreign_key_fields: bool = False, 234 flat_results: bool = True, 235 as_dataframe: bool = False, 236 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 237 ) -> List[dict]: 238 """List objects by chunks. 239 240 Order by arguments on list by chunks will be ignored. 241 242 Args: 243 model_class: 244 Model class of the end-point 245 list_args: 246 filter_dict: 247 Filter dict to be used at the query. Filter elements from 248 query return that satifies all statements of the dictonary. 249 exclude_dict: 250 Exclude dict to be used at the query. Remove elements from 251 query return that satifies all statements of the dictonary. 252 auth_header: 253 Auth header to substitute the microservice original 254 at the request (user impersonation). 255 fields (list): 256 Set the fields to be returned by the list end-point. 257 default_fields (bool): 258 Boolean, if true and fields arguments None will return the 259 default fields set for list by the backend. 260 foreign_key_fields (bool): 261 Return forenging key objects. It will return the fk 262 corresponding object. Ex: `created_by_id` reference to 263 a user `model_class` the correspondent to User will be 264 returned at `created_by`. 265 base_filter_skip (list): 266 List of base query filter to be skiped, it is necessary to 267 be superuser to skip base query filters. 268 n_parallel (int): 269 Number of parallel requests, if None will use the default 270 one. 271 flat_results (bool): 272 The results will be joined on a single list. 273 as_dataframe (bool): 274 If True, returns the results as a pandas DataFrame. 275 chunk_size (int): 276 Number of objects to fetch per query. Defaults to 50000. 277 error_handler (ParallelErrorHandlerInput): 278 Forwarded to ``parallel_call``. 279 filter_errors (bool): 280 Forwarded to ``parallel_call``. Default ``True``. When 281 ``False``, return shape matches ``parallel_call``. 282 283 Returns: 284 Containing objects serialized by list Serializer. 285 286 Raises: 287 No especific raises. 288 """ # NOQA 289 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 290 291 # Convert arguments to list 292 dict_list = self.expand_list_args( 293 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 294 list_model_class = self.convert_to_list( 295 argument=model_class, length=len(list_args)) 296 list_auth_header = self.convert_to_list( 297 argument=auth_header, length=len(list_args)) 298 list_fields = self.convert_to_list( 299 argument=fields, length=len(list_args), 300 force_replicate=True) 301 list_default_fields = self.convert_to_list( 302 argument=default_fields, length=len(list_args)) 303 list_foreign_key_fields = self.convert_to_list( 304 argument=foreign_key_fields, length=len(list_args)) 305 list_base_filter_skip = self.convert_to_list( 306 argument=base_filter_skip, length=len(list_args), 307 force_replicate=True) 308 list_chunk_size = self.convert_to_list( 309 argument=chunk_size, length=len(list_args), 310 force_replicate=True) 311 list_as_dataframe = self.convert_to_list( 312 argument=as_dataframe, length=len(list_args), 313 force_replicate=True) 314 315 column_arg = { 316 'model_class': list_model_class, 317 'auth_header': list_auth_header, 318 'fields': list_fields, 319 'default_fields': list_default_fields, 320 'foreign_key_fields': list_foreign_key_fields, 321 'base_filter_skip': list_base_filter_skip, 322 "chunk_size": list_chunk_size, 323 "as_dataframe": list_as_dataframe 324 } 325 column_arg.update(dict_list) 326 327 function_args = self.transpose_args(dict_list=column_arg) 328 parallel_results = self.parallel_call( 329 function=self.list_by_chunks, function_args=function_args, 330 n_parallel=n_parallel, error_handler=error_handler, 331 filter_errors=filter_errors) 332 return self.finalize_parallel_output( 333 parallel_results, flat_results=flat_results, 334 as_dataframe=as_dataframe)
Abstract class for parallel calls at Pumpwood end-points.
13 def parallel_list(self, model_class: Union[str, List[str]], 14 list_args: List[dict], 15 auth_header: dict = None, fields: list = None, 16 default_fields: bool = False, limit: int = None, 17 foreign_key_fields: bool = False, 18 base_filter_skip: list = None, 19 n_parallel: int = None, 20 flat_results: bool = True, 21 as_dataframe: bool = False, 22 error_handler: ParallelErrorHandlerInput = None, 23 filter_errors: bool = True) -> List[dict]: 24 """List objects with pagination. 25 26 Args: 27 model_class: 28 Model class of the end-point 29 list_args: 30 filter_dict: 31 Filter dict to be used at the query. Filter elements from 32 query return that satifies all statements of the dictonary. 33 exclude_dict: 34 Exclude dict to be used at the query. Remove elements from 35 query return that satifies all statements of the dictonary. 36 order_by: Order results acording to list of strings 37 correspondent to fields. It is possible to use '-' at the 38 begginng of the field name for reverse ordering. Ex.: 39 ['description'] for accendent ordering and ['-description'] 40 for descendent ordering. 41 auth_header: 42 Auth header to substitute the microservice original 43 at the request (user impersonation). 44 fields (list): 45 Set the fields to be returned by the list end-point. 46 default_fields (bool): 47 Boolean, if true and fields arguments None will return the 48 default fields set for list by the backend. 49 limit (int): 50 Set the limit of elements of the returned query. By default, 51 backend usually return 50 elements. 52 foreign_key_fields (bool): 53 Return forenging key objects. It will return the fk 54 corresponding object. Ex: `created_by_id` reference to 55 a user `model_class` the correspondent to User will be 56 returned at `created_by`. 57 base_filter_skip (list): 58 List of base query filter to be skiped, it is necessary to 59 be superuser to skip base query filters. 60 n_parallel (int): 61 Number of parallel requests, if None will use the default 62 one. 63 flat_results (bool): 64 The results will be joined on a single list. 65 as_dataframe (bool): 66 If True, returns the results as a pandas DataFrame. 67 error_handler (ParallelErrorHandlerInput): 68 Forwarded to ``parallel_call``. 69 filter_errors (bool): 70 Forwarded to ``parallel_call``. Default ``True``. When 71 ``False``, return shape matches ``parallel_call``. 72 73 Returns: 74 Containing objects serialized by list Serializer. 75 76 Raises: 77 No especific raises. 78 """ # NOQA 79 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 80 81 # Convert arguments to list 82 dict_list = self.expand_list_args(list_args=list_args) 83 list_model_class = self.convert_to_list( 84 argument=model_class, length=len(list_args)) 85 list_auth_header = self.convert_to_list( 86 argument=auth_header, length=len(list_args)) 87 list_fields = self.convert_to_list( 88 argument=fields, length=len(list_args), 89 force_replicate=True) 90 list_default_fields = self.convert_to_list( 91 argument=default_fields, length=len(list_args)) 92 list_limit = self.convert_to_list( 93 argument=limit, length=len(list_args)) 94 list_foreign_key_fields = self.convert_to_list( 95 argument=foreign_key_fields, length=len(list_args)) 96 list_base_filter_skip = self.convert_to_list( 97 argument=base_filter_skip, length=len(list_args), 98 force_replicate=True) 99 list_as_dataframe = self.convert_to_list( 100 argument=as_dataframe, length=len(list_args), 101 force_replicate=True) 102 103 column_arg = { 104 'model_class': list_model_class, 105 'auth_header': list_auth_header, 106 'fields': list_fields, 107 'default_fields': list_default_fields, 108 'limit': list_limit, 109 'foreign_key_fields': list_foreign_key_fields, 110 'base_filter_skip': list_base_filter_skip, 111 "as_dataframe": list_as_dataframe 112 } 113 column_arg.update(dict_list) 114 115 function_args = self.transpose_args(dict_list=column_arg) 116 parallel_results = self.parallel_call( 117 function=self.list, function_args=function_args, 118 n_parallel=n_parallel, error_handler=error_handler, 119 filter_errors=filter_errors) 120 return self.finalize_parallel_output( 121 parallel_results, flat_results=flat_results)
List objects with pagination.
Arguments:
- model_class: Model class of the end-point
- list_args: filter_dict: Filter dict to be used at the query. Filter elements from query return that satifies all statements of the dictonary. exclude_dict: Exclude dict to be used at the query. Remove elements from query return that satifies all statements of the dictonary. order_by: Order results acording to list of strings correspondent to fields. It is possible to use '-' at the begginng of the field name for reverse ordering. Ex.: ['description'] for accendent ordering and ['-description'] for descendent ordering.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields (list): Set the fields to be returned by the list end-point.
- default_fields (bool): Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- limit (int): Set the limit of elements of the returned query. By default, backend usually return 50 elements.
- foreign_key_fields (bool): Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- flat_results (bool): The results will be joined on a single list.
- as_dataframe (bool): If True, returns the results as a pandas DataFrame.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Containing objects serialized by list Serializer.
Raises:
- No especific raises.
123 def parallel_list_without_pag(self, model_class: Union[str, List[str]], 124 list_args: List[dict], 125 auth_header: dict = None, 126 fields: list = None, 127 default_fields: bool = False, 128 foreign_key_fields: bool = False, 129 base_filter_skip: list = None, 130 n_parallel: int = None, 131 flat_results: bool = True, 132 as_dataframe: bool = False, 133 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 134 ) -> List[dict]: 135 """List objects with pagination. 136 137 Args: 138 model_class: 139 Model class of the end-point 140 list_args: 141 filter_dict: 142 Filter dict to be used at the query. Filter elements from 143 query return that satifies all statements of the dictonary. 144 exclude_dict: 145 Exclude dict to be used at the query. Remove elements from 146 query return that satifies all statements of the dictonary. 147 auth_header: 148 Auth header to substitute the microservice original 149 at the request (user impersonation). 150 fields (list): 151 Set the fields to be returned by the list end-point. 152 default_fields (bool): 153 Boolean, if true and fields arguments None will return the 154 default fields set for list by the backend. 155 foreign_key_fields (bool): 156 Return forenging key objects. It will return the fk 157 corresponding object. Ex: `created_by_id` reference to 158 a user `model_class` the correspondent to User will be 159 returned at `created_by`. 160 base_filter_skip (list): 161 List of base query filter to be skiped, it is necessary to 162 be superuser to skip base query filters. 163 n_parallel (int): 164 Number of parallel requests, if None will use the default 165 one. 166 flat_results (bool): 167 The results will be joined on a single list. 168 as_dataframe (bool): 169 If True, returns the results as a pandas DataFrame. 170 error_handler (ParallelErrorHandlerInput): 171 Forwarded to ``parallel_call``. 172 filter_errors (bool): 173 Forwarded to ``parallel_call``. Default ``True``. When 174 ``False``, return shape matches ``parallel_call``. 175 176 Returns: 177 Containing objects serialized by list Serializer. 178 179 Raises: 180 No especific raises. 181 """ # NOQA 182 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 183 184 # Convert arguments to list 185 dict_list = self.expand_list_args( 186 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 187 list_model_class = self.convert_to_list( 188 argument=model_class, length=len(list_args)) 189 list_auth_header = self.convert_to_list( 190 argument=auth_header, length=len(list_args)) 191 list_fields = self.convert_to_list( 192 argument=fields, length=len(list_args), 193 force_replicate=True) 194 list_default_fields = self.convert_to_list( 195 argument=default_fields, length=len(list_args)) 196 list_foreign_key_fields = self.convert_to_list( 197 argument=foreign_key_fields, length=len(list_args)) 198 list_base_filter_skip = self.convert_to_list( 199 argument=base_filter_skip, length=len(list_args), 200 force_replicate=True) 201 list_as_dataframe = self.convert_to_list( 202 argument=as_dataframe, length=len(list_args), 203 force_replicate=True) 204 205 column_arg = { 206 'model_class': list_model_class, 207 'auth_header': list_auth_header, 208 'fields': list_fields, 209 'default_fields': list_default_fields, 210 'foreign_key_fields': list_foreign_key_fields, 211 'base_filter_skip': list_base_filter_skip, 212 "as_dataframe": list_as_dataframe 213 } 214 column_arg.update(dict_list) 215 216 function_args = self.transpose_args(dict_list=column_arg) 217 parallel_results = self.parallel_call( 218 function=self.list_without_pag, function_args=function_args, 219 n_parallel=n_parallel, error_handler=error_handler, 220 filter_errors=filter_errors) 221 return self.finalize_parallel_output( 222 parallel_results, flat_results=flat_results, 223 as_dataframe=as_dataframe)
List objects with pagination.
Arguments:
- model_class: Model class of the end-point
- list_args: filter_dict: Filter dict to be used at the query. Filter elements from query return that satifies all statements of the dictonary. exclude_dict: Exclude dict to be used at the query. Remove elements from query return that satifies all statements of the dictonary.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields (list): Set the fields to be returned by the list end-point.
- default_fields (bool): Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- foreign_key_fields (bool): Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- flat_results (bool): The results will be joined on a single list.
- as_dataframe (bool): If True, returns the results as a pandas DataFrame.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Containing objects serialized by list Serializer.
Raises:
- No especific raises.
225 def parallel_list_by_chunks(self, model_class: Union[str, List[str]], 226 list_args: List[dict], 227 auth_header: dict = None, 228 fields: list = None, 229 default_fields: bool = False, 230 base_filter_skip: list = None, 231 n_parallel: int = None, 232 chunk_size: int = 50000, 233 foreign_key_fields: bool = False, 234 flat_results: bool = True, 235 as_dataframe: bool = False, 236 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 237 ) -> List[dict]: 238 """List objects by chunks. 239 240 Order by arguments on list by chunks will be ignored. 241 242 Args: 243 model_class: 244 Model class of the end-point 245 list_args: 246 filter_dict: 247 Filter dict to be used at the query. Filter elements from 248 query return that satifies all statements of the dictonary. 249 exclude_dict: 250 Exclude dict to be used at the query. Remove elements from 251 query return that satifies all statements of the dictonary. 252 auth_header: 253 Auth header to substitute the microservice original 254 at the request (user impersonation). 255 fields (list): 256 Set the fields to be returned by the list end-point. 257 default_fields (bool): 258 Boolean, if true and fields arguments None will return the 259 default fields set for list by the backend. 260 foreign_key_fields (bool): 261 Return forenging key objects. It will return the fk 262 corresponding object. Ex: `created_by_id` reference to 263 a user `model_class` the correspondent to User will be 264 returned at `created_by`. 265 base_filter_skip (list): 266 List of base query filter to be skiped, it is necessary to 267 be superuser to skip base query filters. 268 n_parallel (int): 269 Number of parallel requests, if None will use the default 270 one. 271 flat_results (bool): 272 The results will be joined on a single list. 273 as_dataframe (bool): 274 If True, returns the results as a pandas DataFrame. 275 chunk_size (int): 276 Number of objects to fetch per query. Defaults to 50000. 277 error_handler (ParallelErrorHandlerInput): 278 Forwarded to ``parallel_call``. 279 filter_errors (bool): 280 Forwarded to ``parallel_call``. Default ``True``. When 281 ``False``, return shape matches ``parallel_call``. 282 283 Returns: 284 Containing objects serialized by list Serializer. 285 286 Raises: 287 No especific raises. 288 """ # NOQA 289 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 290 291 # Convert arguments to list 292 dict_list = self.expand_list_args( 293 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 294 list_model_class = self.convert_to_list( 295 argument=model_class, length=len(list_args)) 296 list_auth_header = self.convert_to_list( 297 argument=auth_header, length=len(list_args)) 298 list_fields = self.convert_to_list( 299 argument=fields, length=len(list_args), 300 force_replicate=True) 301 list_default_fields = self.convert_to_list( 302 argument=default_fields, length=len(list_args)) 303 list_foreign_key_fields = self.convert_to_list( 304 argument=foreign_key_fields, length=len(list_args)) 305 list_base_filter_skip = self.convert_to_list( 306 argument=base_filter_skip, length=len(list_args), 307 force_replicate=True) 308 list_chunk_size = self.convert_to_list( 309 argument=chunk_size, length=len(list_args), 310 force_replicate=True) 311 list_as_dataframe = self.convert_to_list( 312 argument=as_dataframe, length=len(list_args), 313 force_replicate=True) 314 315 column_arg = { 316 'model_class': list_model_class, 317 'auth_header': list_auth_header, 318 'fields': list_fields, 319 'default_fields': list_default_fields, 320 'foreign_key_fields': list_foreign_key_fields, 321 'base_filter_skip': list_base_filter_skip, 322 "chunk_size": list_chunk_size, 323 "as_dataframe": list_as_dataframe 324 } 325 column_arg.update(dict_list) 326 327 function_args = self.transpose_args(dict_list=column_arg) 328 parallel_results = self.parallel_call( 329 function=self.list_by_chunks, function_args=function_args, 330 n_parallel=n_parallel, error_handler=error_handler, 331 filter_errors=filter_errors) 332 return self.finalize_parallel_output( 333 parallel_results, flat_results=flat_results, 334 as_dataframe=as_dataframe)
List objects by chunks.
Order by arguments on list by chunks will be ignored.
Arguments:
- model_class: Model class of the end-point
- list_args: filter_dict: Filter dict to be used at the query. Filter elements from query return that satifies all statements of the dictonary. exclude_dict: Exclude dict to be used at the query. Remove elements from query return that satifies all statements of the dictonary.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields (list): Set the fields to be returned by the list end-point.
- default_fields (bool): Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- foreign_key_fields (bool): Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- flat_results (bool): The results will be joined on a single list.
- as_dataframe (bool): If True, returns the results as a pandas DataFrame.
- chunk_size (int): Number of objects to fetch per query. Defaults to 50000.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Containing objects serialized by list Serializer.
Raises:
- No especific raises.
9class ABCParallelRetriveMicroservice(ABCParallelBaseMicroservice): 10 """Abstract class for parallel calls at Pumpwood end-points.""" 11 12 def parallel_retrieve(self, model_class: str | list[str], 13 list_pk: list[int], 14 default_fields: bool | list[bool] = False, 15 foreign_key_fields: bool | list[bool] = False, 16 related_fields: bool | list[bool] = False, 17 fields: list[str] | list[list[str]] = None, 18 auth_header: dict | list[dict] = None, 19 use_disk_cache: bool | list[bool] = False, 20 use_app_cache: bool | list[bool] = False, 21 disk_cache_expire: int | list[int] = None, 22 base_filter_skip: list[str] | list[list[str]] = None, 23 n_parallel: int | None = None, 24 error_handler: ParallelErrorHandlerInput = 25 None, filter_errors: bool = True) -> list[dict]: 26 """Retrieve an object from PumpWood. 27 28 Function to get object serialized by retrieve end-point 29 (more detailed data). 30 31 Args: 32 model_class: 33 Model class of the end-point 34 list_pk: 35 Object pk 36 auth_header: 37 Auth header to substitute the microservice original 38 at the request (user impersonation). 39 fields: 40 Set the fields to be returned by the list end-point. 41 default_fields: 42 Boolean, if true and fields arguments None will return the 43 default fields set for list by the backend. 44 foreign_key_fields: 45 Return forenging key objects. It will return the fk 46 corresponding object. Ex: `created_by_id` reference to 47 a user `model_class` the correspondent to User will be 48 returned at `created_by`. 49 related_fields: 50 Return related fields objects. Related field objects are 51 objects that have a forenging key associated with this 52 model_class, results will be returned as a list of 53 dictionaries usually in a field with `_set` at end. 54 Returning related_fields consume backend resorces, use 55 carefully. 56 use_disk_cache (bool): 57 If set true, get request will use local cache to reduce 58 the requests to the backend. 59 use_app_cache (bool): 60 If True, the GET request will use the cache of the application. 61 Defaults to False. 62 disk_cache_expire (int): 63 Time in seconds to expire the cache, it None it will 64 use de default set be PumpwoodCache. 65 base_filter_skip (list): 66 List of base query filter to be skiped, it is necessary to 67 be superuser to skip base query filters. 68 n_parallel (int | None): 69 N parallel request that will be done on backend. 70 error_handler (ParallelErrorHandlerInput): 71 Forwarded to ``parallel_call``. 72 filter_errors (bool): 73 Forwarded to ``parallel_call``. Default ``True``. When 74 ``False``, return shape matches ``parallel_call``. 75 76 Returns: 77 Return object with the correspondent pk. 78 79 Raises: 80 PumpWoodObjectDoesNotExist: 81 If pk not found on database. 82 """ 83 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 84 85 list_model_class = self.convert_to_list( 86 argument=model_class, length=len(list_pk)) 87 list_default_fields = self.convert_to_list( 88 argument=default_fields, length=len(list_pk)) 89 list_foreign_key_fields = self.convert_to_list( 90 argument=foreign_key_fields, length=len(list_pk)) 91 list_related_fields = self.convert_to_list( 92 argument=related_fields, length=len(list_pk)) 93 list_fields = self.convert_to_list( 94 argument=fields, length=len(list_pk), 95 force_replicate=True) 96 list_auth_header = self.convert_to_list( 97 argument=auth_header, length=len(list_pk)) 98 list_use_disk_cache = self.convert_to_list( 99 argument=use_disk_cache, length=len(list_pk)) 100 list_use_app_cache = self.convert_to_list( 101 argument=use_app_cache, length=len(list_pk)) 102 list_disk_cache_expire = self.convert_to_list( 103 argument=disk_cache_expire, length=len(list_pk)) 104 list_base_filter_skip = self.convert_to_list( 105 argument=base_filter_skip, length=len(list_pk), 106 force_replicate=True) 107 108 column_arg = { 109 'model_class': list_model_class, 110 'pk': list_pk, 111 'default_fields': list_default_fields, 112 'foreign_key_fields': list_foreign_key_fields, 113 'related_fields': list_related_fields, 114 'fields': list_fields, 115 'auth_header': list_auth_header, 116 'use_disk_cache': list_use_disk_cache, 117 'use_app_cache': list_use_app_cache, 118 'disk_cache_expire': list_disk_cache_expire, 119 'base_filter_skip': list_base_filter_skip} 120 121 function_args = self.transpose_args(dict_list=column_arg) 122 return self.parallel_call( 123 function=self.retrieve, function_args=function_args, 124 n_parallel=n_parallel, error_handler=error_handler, 125 filter_errors=filter_errors) 126 127 def parallel_list_one(self, model_class: str | list[str], 128 list_pk: list[int], 129 default_fields: bool | list[bool] = True, 130 foreign_key_fields: bool | list[bool] = False, 131 related_fields: bool | list[bool] = False, 132 fields: list[str] | list[list[str]] = None, 133 auth_header: dict | list[dict] = None, 134 use_disk_cache: bool | list[bool] = False, 135 use_app_cache: bool | list[bool] = False, 136 disk_cache_expire: int | list[int] = None, 137 base_filter_skip: list[str] | list[list[str]] = None, 138 n_parallel: int | None = None, 139 error_handler: ParallelErrorHandlerInput = 140 None, filter_errors: bool = True 141 ) -> list[dict]: 142 """Retrieve an object from PumpWood. 143 144 Function to get object serialized by retrieve end-point 145 (more detailed data). 146 147 Args: 148 model_class: 149 Model class of the end-point 150 list_pk: 151 Object pk 152 auth_header: 153 Auth header to substitute the microservice original 154 at the request (user impersonation). 155 fields: 156 Set the fields to be returned by the list end-point. 157 default_fields: 158 Boolean, if true and fields arguments None will return the 159 default fields set for list by the backend. 160 foreign_key_fields: 161 Return forenging key objects. It will return the fk 162 corresponding object. Ex: `created_by_id` reference to 163 a user `model_class` the correspondent to User will be 164 returned at `created_by`. 165 related_fields: 166 Return related fields objects. Related field objects are 167 objects that have a forenging key associated with this 168 model_class, results will be returned as a list of 169 dictionaries usually in a field with `_set` at end. 170 Returning related_fields consume backend resorces, use 171 carefully. 172 use_disk_cache (bool): 173 If set true, get request will use local cache to reduce 174 the requests to the backend. 175 use_app_cache (bool): 176 If True, the GET request will use the cache of the application. 177 Defaults to False. 178 disk_cache_expire (int): 179 Time in seconds to expire the cache, it None it will 180 use de default set be PumpwoodCache. 181 base_filter_skip (list): 182 List of base query filter to be skiped, it is necessary to 183 be superuser to skip base query filters. 184 n_parallel (int | None): 185 N parallel request that will be done on backend. 186 error_handler (ParallelErrorHandlerInput): 187 Forwarded to ``parallel_call``. 188 filter_errors (bool): 189 Forwarded to ``parallel_call``. Default ``True``. When 190 ``False``, return shape matches ``parallel_call``. 191 192 Returns: 193 Return object with the correspondent pk. 194 195 Raises: 196 PumpWoodObjectDoesNotExist: 197 If pk not found on database. 198 """ 199 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 200 201 list_model_class = self.convert_to_list( 202 argument=model_class, length=len(list_pk)) 203 list_default_fields = self.convert_to_list( 204 argument=default_fields, length=len(list_pk)) 205 list_foreign_key_fields = self.convert_to_list( 206 argument=foreign_key_fields, length=len(list_pk)) 207 list_related_fields = self.convert_to_list( 208 argument=related_fields, length=len(list_pk)) 209 list_fields = self.convert_to_list( 210 argument=fields, length=len(list_pk), 211 force_replicate=True) 212 list_auth_header = self.convert_to_list( 213 argument=auth_header, length=len(list_pk)) 214 list_use_disk_cache = self.convert_to_list( 215 argument=use_disk_cache, length=len(list_pk)) 216 list_use_app_cache = self.convert_to_list( 217 argument=use_app_cache, length=len(list_pk)) 218 list_disk_cache_expire = self.convert_to_list( 219 argument=disk_cache_expire, length=len(list_pk)) 220 list_base_filter_skip = self.convert_to_list( 221 argument=base_filter_skip, length=len(list_pk), 222 force_replicate=True) 223 224 column_arg = { 225 'model_class': list_model_class, 226 'pk': list_pk, 227 'default_fields': list_default_fields, 228 'foreign_key_fields': list_foreign_key_fields, 229 'related_fields': list_related_fields, 230 'fields': list_fields, 231 'auth_header': list_auth_header, 232 'use_disk_cache': list_use_disk_cache, 233 'use_app_cache': list_use_app_cache, 234 'disk_cache_expire': list_disk_cache_expire, 235 'base_filter_skip': list_base_filter_skip} 236 237 function_args = self.transpose_args(dict_list=column_arg) 238 return self.parallel_call( 239 function=self.list_one, function_args=function_args, 240 n_parallel=n_parallel, error_handler=error_handler, 241 filter_errors=filter_errors) 242 243 def parallel_retrieve_file(self, model_class: str | list[str], 244 list_pk: list[int], 245 file_field: str | list[str], 246 auth_header: dict | list[dict] = None, 247 save_file: bool | list[bool] = True, 248 save_path: str | list[str] = "./", 249 file_name: str | list[str] = None, 250 if_exists: str | list[str] = "fail", 251 base_filter_skip: list[str] | list[list[str]] = None, #NOQA 252 n_parallel: int | None = None, 253 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 254 ) -> list[str] | list[dict]: 255 """Retrieve a file from PumpWood. 256 257 This function will retrieve file as a single request, depending on the 258 size of the files it would be preferred to use streaming end-point. 259 260 Args: 261 model_class: 262 Class of the model to retrieve file. 263 list_pk: 264 Pk of the object associeted file. 265 file_field: 266 Field of the file to be downloaded. 267 auth_header: 268 Dictionary containing the auth header. 269 save_file: 270 If data is to be saved as file or return get 271 response. 272 save_path: 273 Path of the directory to save file. 274 file_name: 275 Name of the file, if None it will have same name as 276 saved in PumpWood. 277 if_exists: 278 Values must be in {'fail', 'change_name', 'overwrite', 'skip'}. 279 Set what to do if there is a file with same name. Skip 280 will not download file if there is already with same 281 os.path.join(save_path, file_name), file_name must be set 282 for skip argument. 283 auth_header: 284 Auth header to substitute the microservice original 285 at the request (user impersonation). 286 base_filter_skip (list): 287 List of base query filter to be skiped, it is necessary to 288 be superuser to skip base query filters. 289 n_parallel (int): 290 Number of parallel requests, if None will use the default 291 one. 292 error_handler (ParallelErrorHandlerInput): 293 Forwarded to ``parallel_call``. 294 filter_errors (bool): 295 Forwarded to ``parallel_call``. Default ``True``. When 296 ``False``, return shape matches ``parallel_call``. 297 298 Returns: 299 May return the file name if save_file=True; If false will return 300 a dictonary with keys `filename` with original file name and 301 `content` with binary data of file content. 302 303 Raises: 304 PumpWoodForbidden: 305 'storage_object attribute not set for view, file operations 306 are disable'. This indicates that storage for this backend 307 was not configured, so it is not possible to make storage 308 operations, 309 PumpWoodForbidden: 310 'file_field must be set on self.file_fields dictionary'. This 311 indicates that the `file_field` parameter is not listed as 312 a file field on the backend. 313 PumpWoodObjectDoesNotExist: 314 'field [{}] not found or null at object'. This indicates that 315 the file field requested is not present on object fields. 316 PumpWoodObjectDoesNotExist: 317 'Object not found in storage [{}]'. This indicates that the 318 file associated with file_field is not avaiable at the 319 storage. This should not ocorrur, it might have a manual 320 update at the model_class table or manual removal/rename of 321 files on storage. 322 """ 323 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 324 325 # Convert arguments to list 326 list_model_class = self.convert_to_list( 327 argument=model_class, length=len(list_pk)) 328 list_file_field = self.convert_to_list( 329 argument=file_field, length=len(list_pk)) 330 list_auth_header = self.convert_to_list( 331 argument=auth_header, length=len(list_pk)) 332 list_save_file = self.convert_to_list( 333 argument=save_file, length=len(list_pk)) 334 list_save_path = self.convert_to_list( 335 argument=save_path, length=len(list_pk)) 336 list_file_name = self.convert_to_list( 337 argument=file_name, length=len(list_pk)) 338 list_if_exists = self.convert_to_list( 339 argument=if_exists, length=len(list_pk)) 340 list_base_filter_skip = self.convert_to_list( 341 argument=base_filter_skip, length=len(list_pk), 342 force_replicate=True) 343 344 column_arg = { 345 'model_class': list_model_class, 346 'pk': list_pk, 347 'file_field': list_file_field, 348 'auth_header': list_auth_header, 349 'save_file': list_save_file, 350 'save_path': list_save_path, 351 'file_name': list_file_name, 352 'if_exists': list_if_exists, 353 'base_filter_skip': list_base_filter_skip} 354 function_args = self.transpose_args(dict_list=column_arg) 355 return self.parallel_call( 356 function=self.retrieve_file, function_args=function_args, 357 n_parallel=n_parallel, error_handler=error_handler, 358 filter_errors=filter_errors) 359 360 def parallel_retrieve_streaming_file(self, model_class: str, 361 list_pk: list[int], 362 file_field: str | list[str], 363 file_name: str | list[str], 364 auth_header: dict | list[dict] = None, 365 save_path: str | list[str] = "./", 366 if_exists: str | list[str] = "fail", 367 base_filter_skip: list | list[list] = None, # NOQA 368 n_parallel: int | None = None, 369 error_handler: ParallelErrorHandlerInput = None, # NOQA 370 filter_errors: bool = True 371 ) -> str: 372 """Retrieve a file from PumpWood using streaming to retrieve content. 373 374 This funcion uses file streaming to retrieve file content, it should be 375 prefered when dealing with large (bigger than 10Mb) files transfer. 376 Using this end-point the file is not loaded on backend memory content 377 is transfered by chucks that are read at the storage and transfered 378 to user. 379 380 It will necessarily save the content as a file, there is not the 381 possibility of retrieving the content directly from request. 382 383 Args: 384 model_class: 385 Class of the model to retrieve file. 386 list_pk (list): 387 Pk of the object associeted file. 388 file_field: 389 Field of the file to be downloaded. 390 auth_header: 391 Dictionary containing the auth header. 392 save_path: 393 Path of the directory to save file. 394 file_name: 395 Name of the file, if None it will have same name as 396 saved in PumpWood. 397 if_exists: 398 Values must be in {'fail', 'change_name', 'overwrite'}. 399 Set what to do if there is a file with same name. 400 auth_header: 401 Auth header to substitute the microservice original 402 at the request (user impersonation). 403 base_filter_skip (list): 404 List of base query filter to be skiped, it is necessary to 405 be superuser to skip base query filters. 406 n_parallel (int): 407 Number of parallel requests, if None will use the default 408 one. 409 error_handler (ParallelErrorHandlerInput): 410 Forwarded to ``parallel_call``. 411 filter_errors (bool): 412 Forwarded to ``parallel_call``. Default ``True``. When 413 ``False``, return shape matches ``parallel_call``. 414 415 Returns: 416 Returns the file path that recived the file content. 417 418 Raises: 419 PumpWoodForbidden: 420 'storage_object attribute not set for view, file operations 421 are disable'. This indicates that storage for this backend 422 was not configured, so it is not possible to make storage 423 operations, 424 PumpWoodForbidden: 425 'file_field must be set on self.file_fields dictionary'. This 426 indicates that the `file_field` parameter is not listed as 427 a file field on the backend. 428 PumpWoodObjectDoesNotExist: 429 'field [{}] not found or null at object'. This indicates that 430 the file field requested is not present on object fields. 431 PumpWoodObjectDoesNotExist: 432 'Object not found in storage [{}]'. This indicates that the 433 file associated with file_field is not avaiable at the 434 storage. This should not ocorrur, it might have a manual 435 update at the model_class table or manual removal/rename of 436 files on storage. 437 """ 438 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 439 440 # Convert arguments to list 441 list_model_class = self.convert_to_list( 442 argument=model_class, length=len(list_pk)) 443 list_file_field = self.convert_to_list( 444 argument=file_field, length=len(list_pk)) 445 list_file_name = self.convert_to_list( 446 argument=file_name, length=len(list_pk)) 447 list_auth_header = self.convert_to_list( 448 argument=auth_header, length=len(list_pk)) 449 list_save_path = self.convert_to_list( 450 argument=save_path, length=len(list_pk)) 451 list_if_exists = self.convert_to_list( 452 argument=if_exists, length=len(list_pk)) 453 list_base_filter_skip = self.convert_to_list( 454 argument=base_filter_skip, length=len(list_pk), 455 force_replicate=True) 456 457 column_arg = { 458 'model_class': list_model_class, 459 'pk': list_pk, 460 'file_field': list_file_field, 461 'file_name': list_file_name, 462 'auth_header': list_auth_header, 463 'save_path': list_save_path, 464 'if_exists': list_if_exists, 465 'base_filter_skip': list_base_filter_skip, 466 } 467 function_args = self.transpose_args(dict_list=column_arg) 468 return self.parallel_call( 469 function=self.retrieve_streaming_file, function_args=function_args, 470 n_parallel=n_parallel, error_handler=error_handler, 471 filter_errors=filter_errors)
Abstract class for parallel calls at Pumpwood end-points.
12 def parallel_retrieve(self, model_class: str | list[str], 13 list_pk: list[int], 14 default_fields: bool | list[bool] = False, 15 foreign_key_fields: bool | list[bool] = False, 16 related_fields: bool | list[bool] = False, 17 fields: list[str] | list[list[str]] = None, 18 auth_header: dict | list[dict] = None, 19 use_disk_cache: bool | list[bool] = False, 20 use_app_cache: bool | list[bool] = False, 21 disk_cache_expire: int | list[int] = None, 22 base_filter_skip: list[str] | list[list[str]] = None, 23 n_parallel: int | None = None, 24 error_handler: ParallelErrorHandlerInput = 25 None, filter_errors: bool = True) -> list[dict]: 26 """Retrieve an object from PumpWood. 27 28 Function to get object serialized by retrieve end-point 29 (more detailed data). 30 31 Args: 32 model_class: 33 Model class of the end-point 34 list_pk: 35 Object pk 36 auth_header: 37 Auth header to substitute the microservice original 38 at the request (user impersonation). 39 fields: 40 Set the fields to be returned by the list end-point. 41 default_fields: 42 Boolean, if true and fields arguments None will return the 43 default fields set for list by the backend. 44 foreign_key_fields: 45 Return forenging key objects. It will return the fk 46 corresponding object. Ex: `created_by_id` reference to 47 a user `model_class` the correspondent to User will be 48 returned at `created_by`. 49 related_fields: 50 Return related fields objects. Related field objects are 51 objects that have a forenging key associated with this 52 model_class, results will be returned as a list of 53 dictionaries usually in a field with `_set` at end. 54 Returning related_fields consume backend resorces, use 55 carefully. 56 use_disk_cache (bool): 57 If set true, get request will use local cache to reduce 58 the requests to the backend. 59 use_app_cache (bool): 60 If True, the GET request will use the cache of the application. 61 Defaults to False. 62 disk_cache_expire (int): 63 Time in seconds to expire the cache, it None it will 64 use de default set be PumpwoodCache. 65 base_filter_skip (list): 66 List of base query filter to be skiped, it is necessary to 67 be superuser to skip base query filters. 68 n_parallel (int | None): 69 N parallel request that will be done on backend. 70 error_handler (ParallelErrorHandlerInput): 71 Forwarded to ``parallel_call``. 72 filter_errors (bool): 73 Forwarded to ``parallel_call``. Default ``True``. When 74 ``False``, return shape matches ``parallel_call``. 75 76 Returns: 77 Return object with the correspondent pk. 78 79 Raises: 80 PumpWoodObjectDoesNotExist: 81 If pk not found on database. 82 """ 83 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 84 85 list_model_class = self.convert_to_list( 86 argument=model_class, length=len(list_pk)) 87 list_default_fields = self.convert_to_list( 88 argument=default_fields, length=len(list_pk)) 89 list_foreign_key_fields = self.convert_to_list( 90 argument=foreign_key_fields, length=len(list_pk)) 91 list_related_fields = self.convert_to_list( 92 argument=related_fields, length=len(list_pk)) 93 list_fields = self.convert_to_list( 94 argument=fields, length=len(list_pk), 95 force_replicate=True) 96 list_auth_header = self.convert_to_list( 97 argument=auth_header, length=len(list_pk)) 98 list_use_disk_cache = self.convert_to_list( 99 argument=use_disk_cache, length=len(list_pk)) 100 list_use_app_cache = self.convert_to_list( 101 argument=use_app_cache, length=len(list_pk)) 102 list_disk_cache_expire = self.convert_to_list( 103 argument=disk_cache_expire, length=len(list_pk)) 104 list_base_filter_skip = self.convert_to_list( 105 argument=base_filter_skip, length=len(list_pk), 106 force_replicate=True) 107 108 column_arg = { 109 'model_class': list_model_class, 110 'pk': list_pk, 111 'default_fields': list_default_fields, 112 'foreign_key_fields': list_foreign_key_fields, 113 'related_fields': list_related_fields, 114 'fields': list_fields, 115 'auth_header': list_auth_header, 116 'use_disk_cache': list_use_disk_cache, 117 'use_app_cache': list_use_app_cache, 118 'disk_cache_expire': list_disk_cache_expire, 119 'base_filter_skip': list_base_filter_skip} 120 121 function_args = self.transpose_args(dict_list=column_arg) 122 return self.parallel_call( 123 function=self.retrieve, function_args=function_args, 124 n_parallel=n_parallel, error_handler=error_handler, 125 filter_errors=filter_errors)
Retrieve an object from PumpWood.
Function to get object serialized by retrieve end-point (more detailed data).
Arguments:
- model_class: Model class of the end-point
- list_pk: Object pk
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields: Set the fields to be returned by the list end-point.
- default_fields: Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- foreign_key_fields: Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - related_fields: Return related fields objects. Related field objects are
objects that have a forenging key associated with this
model_class, results will be returned as a list of
dictionaries usually in a field with
_setat end. Returning related_fields consume backend resorces, use carefully. - use_disk_cache (bool): If set true, get request will use local cache to reduce the requests to the backend.
- use_app_cache (bool): If True, the GET request will use the cache of the application. Defaults to False.
- disk_cache_expire (int): Time in seconds to expire the cache, it None it will use de default set be PumpwoodCache.
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int | None): N parallel request that will be done on backend.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Return object with the correspondent pk.
Raises:
- PumpWoodObjectDoesNotExist: If pk not found on database.
127 def parallel_list_one(self, model_class: str | list[str], 128 list_pk: list[int], 129 default_fields: bool | list[bool] = True, 130 foreign_key_fields: bool | list[bool] = False, 131 related_fields: bool | list[bool] = False, 132 fields: list[str] | list[list[str]] = None, 133 auth_header: dict | list[dict] = None, 134 use_disk_cache: bool | list[bool] = False, 135 use_app_cache: bool | list[bool] = False, 136 disk_cache_expire: int | list[int] = None, 137 base_filter_skip: list[str] | list[list[str]] = None, 138 n_parallel: int | None = None, 139 error_handler: ParallelErrorHandlerInput = 140 None, filter_errors: bool = True 141 ) -> list[dict]: 142 """Retrieve an object from PumpWood. 143 144 Function to get object serialized by retrieve end-point 145 (more detailed data). 146 147 Args: 148 model_class: 149 Model class of the end-point 150 list_pk: 151 Object pk 152 auth_header: 153 Auth header to substitute the microservice original 154 at the request (user impersonation). 155 fields: 156 Set the fields to be returned by the list end-point. 157 default_fields: 158 Boolean, if true and fields arguments None will return the 159 default fields set for list by the backend. 160 foreign_key_fields: 161 Return forenging key objects. It will return the fk 162 corresponding object. Ex: `created_by_id` reference to 163 a user `model_class` the correspondent to User will be 164 returned at `created_by`. 165 related_fields: 166 Return related fields objects. Related field objects are 167 objects that have a forenging key associated with this 168 model_class, results will be returned as a list of 169 dictionaries usually in a field with `_set` at end. 170 Returning related_fields consume backend resorces, use 171 carefully. 172 use_disk_cache (bool): 173 If set true, get request will use local cache to reduce 174 the requests to the backend. 175 use_app_cache (bool): 176 If True, the GET request will use the cache of the application. 177 Defaults to False. 178 disk_cache_expire (int): 179 Time in seconds to expire the cache, it None it will 180 use de default set be PumpwoodCache. 181 base_filter_skip (list): 182 List of base query filter to be skiped, it is necessary to 183 be superuser to skip base query filters. 184 n_parallel (int | None): 185 N parallel request that will be done on backend. 186 error_handler (ParallelErrorHandlerInput): 187 Forwarded to ``parallel_call``. 188 filter_errors (bool): 189 Forwarded to ``parallel_call``. Default ``True``. When 190 ``False``, return shape matches ``parallel_call``. 191 192 Returns: 193 Return object with the correspondent pk. 194 195 Raises: 196 PumpWoodObjectDoesNotExist: 197 If pk not found on database. 198 """ 199 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 200 201 list_model_class = self.convert_to_list( 202 argument=model_class, length=len(list_pk)) 203 list_default_fields = self.convert_to_list( 204 argument=default_fields, length=len(list_pk)) 205 list_foreign_key_fields = self.convert_to_list( 206 argument=foreign_key_fields, length=len(list_pk)) 207 list_related_fields = self.convert_to_list( 208 argument=related_fields, length=len(list_pk)) 209 list_fields = self.convert_to_list( 210 argument=fields, length=len(list_pk), 211 force_replicate=True) 212 list_auth_header = self.convert_to_list( 213 argument=auth_header, length=len(list_pk)) 214 list_use_disk_cache = self.convert_to_list( 215 argument=use_disk_cache, length=len(list_pk)) 216 list_use_app_cache = self.convert_to_list( 217 argument=use_app_cache, length=len(list_pk)) 218 list_disk_cache_expire = self.convert_to_list( 219 argument=disk_cache_expire, length=len(list_pk)) 220 list_base_filter_skip = self.convert_to_list( 221 argument=base_filter_skip, length=len(list_pk), 222 force_replicate=True) 223 224 column_arg = { 225 'model_class': list_model_class, 226 'pk': list_pk, 227 'default_fields': list_default_fields, 228 'foreign_key_fields': list_foreign_key_fields, 229 'related_fields': list_related_fields, 230 'fields': list_fields, 231 'auth_header': list_auth_header, 232 'use_disk_cache': list_use_disk_cache, 233 'use_app_cache': list_use_app_cache, 234 'disk_cache_expire': list_disk_cache_expire, 235 'base_filter_skip': list_base_filter_skip} 236 237 function_args = self.transpose_args(dict_list=column_arg) 238 return self.parallel_call( 239 function=self.list_one, function_args=function_args, 240 n_parallel=n_parallel, error_handler=error_handler, 241 filter_errors=filter_errors)
Retrieve an object from PumpWood.
Function to get object serialized by retrieve end-point (more detailed data).
Arguments:
- model_class: Model class of the end-point
- list_pk: Object pk
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields: Set the fields to be returned by the list end-point.
- default_fields: Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- foreign_key_fields: Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - related_fields: Return related fields objects. Related field objects are
objects that have a forenging key associated with this
model_class, results will be returned as a list of
dictionaries usually in a field with
_setat end. Returning related_fields consume backend resorces, use carefully. - use_disk_cache (bool): If set true, get request will use local cache to reduce the requests to the backend.
- use_app_cache (bool): If True, the GET request will use the cache of the application. Defaults to False.
- disk_cache_expire (int): Time in seconds to expire the cache, it None it will use de default set be PumpwoodCache.
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int | None): N parallel request that will be done on backend.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Return object with the correspondent pk.
Raises:
- PumpWoodObjectDoesNotExist: If pk not found on database.
243 def parallel_retrieve_file(self, model_class: str | list[str], 244 list_pk: list[int], 245 file_field: str | list[str], 246 auth_header: dict | list[dict] = None, 247 save_file: bool | list[bool] = True, 248 save_path: str | list[str] = "./", 249 file_name: str | list[str] = None, 250 if_exists: str | list[str] = "fail", 251 base_filter_skip: list[str] | list[list[str]] = None, #NOQA 252 n_parallel: int | None = None, 253 error_handler: ParallelErrorHandlerInput = None, filter_errors: bool = True 254 ) -> list[str] | list[dict]: 255 """Retrieve a file from PumpWood. 256 257 This function will retrieve file as a single request, depending on the 258 size of the files it would be preferred to use streaming end-point. 259 260 Args: 261 model_class: 262 Class of the model to retrieve file. 263 list_pk: 264 Pk of the object associeted file. 265 file_field: 266 Field of the file to be downloaded. 267 auth_header: 268 Dictionary containing the auth header. 269 save_file: 270 If data is to be saved as file or return get 271 response. 272 save_path: 273 Path of the directory to save file. 274 file_name: 275 Name of the file, if None it will have same name as 276 saved in PumpWood. 277 if_exists: 278 Values must be in {'fail', 'change_name', 'overwrite', 'skip'}. 279 Set what to do if there is a file with same name. Skip 280 will not download file if there is already with same 281 os.path.join(save_path, file_name), file_name must be set 282 for skip argument. 283 auth_header: 284 Auth header to substitute the microservice original 285 at the request (user impersonation). 286 base_filter_skip (list): 287 List of base query filter to be skiped, it is necessary to 288 be superuser to skip base query filters. 289 n_parallel (int): 290 Number of parallel requests, if None will use the default 291 one. 292 error_handler (ParallelErrorHandlerInput): 293 Forwarded to ``parallel_call``. 294 filter_errors (bool): 295 Forwarded to ``parallel_call``. Default ``True``. When 296 ``False``, return shape matches ``parallel_call``. 297 298 Returns: 299 May return the file name if save_file=True; If false will return 300 a dictonary with keys `filename` with original file name and 301 `content` with binary data of file content. 302 303 Raises: 304 PumpWoodForbidden: 305 'storage_object attribute not set for view, file operations 306 are disable'. This indicates that storage for this backend 307 was not configured, so it is not possible to make storage 308 operations, 309 PumpWoodForbidden: 310 'file_field must be set on self.file_fields dictionary'. This 311 indicates that the `file_field` parameter is not listed as 312 a file field on the backend. 313 PumpWoodObjectDoesNotExist: 314 'field [{}] not found or null at object'. This indicates that 315 the file field requested is not present on object fields. 316 PumpWoodObjectDoesNotExist: 317 'Object not found in storage [{}]'. This indicates that the 318 file associated with file_field is not avaiable at the 319 storage. This should not ocorrur, it might have a manual 320 update at the model_class table or manual removal/rename of 321 files on storage. 322 """ 323 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 324 325 # Convert arguments to list 326 list_model_class = self.convert_to_list( 327 argument=model_class, length=len(list_pk)) 328 list_file_field = self.convert_to_list( 329 argument=file_field, length=len(list_pk)) 330 list_auth_header = self.convert_to_list( 331 argument=auth_header, length=len(list_pk)) 332 list_save_file = self.convert_to_list( 333 argument=save_file, length=len(list_pk)) 334 list_save_path = self.convert_to_list( 335 argument=save_path, length=len(list_pk)) 336 list_file_name = self.convert_to_list( 337 argument=file_name, length=len(list_pk)) 338 list_if_exists = self.convert_to_list( 339 argument=if_exists, length=len(list_pk)) 340 list_base_filter_skip = self.convert_to_list( 341 argument=base_filter_skip, length=len(list_pk), 342 force_replicate=True) 343 344 column_arg = { 345 'model_class': list_model_class, 346 'pk': list_pk, 347 'file_field': list_file_field, 348 'auth_header': list_auth_header, 349 'save_file': list_save_file, 350 'save_path': list_save_path, 351 'file_name': list_file_name, 352 'if_exists': list_if_exists, 353 'base_filter_skip': list_base_filter_skip} 354 function_args = self.transpose_args(dict_list=column_arg) 355 return self.parallel_call( 356 function=self.retrieve_file, function_args=function_args, 357 n_parallel=n_parallel, error_handler=error_handler, 358 filter_errors=filter_errors)
Retrieve a file from PumpWood.
This function will retrieve file as a single request, depending on the size of the files it would be preferred to use streaming end-point.
Arguments:
- model_class: Class of the model to retrieve file.
- list_pk: Pk of the object associeted file.
- file_field: Field of the file to be downloaded.
- auth_header: Dictionary containing the auth header.
- save_file: If data is to be saved as file or return get response.
- save_path: Path of the directory to save file.
- file_name: Name of the file, if None it will have same name as saved in PumpWood.
- if_exists: Values must be in {'fail', 'change_name', 'overwrite', 'skip'}. Set what to do if there is a file with same name. Skip will not download file if there is already with same os.path.join(save_path, file_name), file_name must be set for skip argument.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
May return the file name if save_file=True; If false will return a dictonary with keys
filenamewith original file name andcontentwith binary data of file content.
Raises:
- PumpWoodForbidden: 'storage_object attribute not set for view, file operations are disable'. This indicates that storage for this backend was not configured, so it is not possible to make storage operations,
- PumpWoodForbidden: 'file_field must be set on self.file_fields dictionary'. This
indicates that the
file_fieldparameter is not listed as a file field on the backend. - PumpWoodObjectDoesNotExist: 'field [{}] not found or null at object'. This indicates that the file field requested is not present on object fields.
- PumpWoodObjectDoesNotExist: 'Object not found in storage [{}]'. This indicates that the file associated with file_field is not avaiable at the storage. This should not ocorrur, it might have a manual update at the model_class table or manual removal/rename of files on storage.
360 def parallel_retrieve_streaming_file(self, model_class: str, 361 list_pk: list[int], 362 file_field: str | list[str], 363 file_name: str | list[str], 364 auth_header: dict | list[dict] = None, 365 save_path: str | list[str] = "./", 366 if_exists: str | list[str] = "fail", 367 base_filter_skip: list | list[list] = None, # NOQA 368 n_parallel: int | None = None, 369 error_handler: ParallelErrorHandlerInput = None, # NOQA 370 filter_errors: bool = True 371 ) -> str: 372 """Retrieve a file from PumpWood using streaming to retrieve content. 373 374 This funcion uses file streaming to retrieve file content, it should be 375 prefered when dealing with large (bigger than 10Mb) files transfer. 376 Using this end-point the file is not loaded on backend memory content 377 is transfered by chucks that are read at the storage and transfered 378 to user. 379 380 It will necessarily save the content as a file, there is not the 381 possibility of retrieving the content directly from request. 382 383 Args: 384 model_class: 385 Class of the model to retrieve file. 386 list_pk (list): 387 Pk of the object associeted file. 388 file_field: 389 Field of the file to be downloaded. 390 auth_header: 391 Dictionary containing the auth header. 392 save_path: 393 Path of the directory to save file. 394 file_name: 395 Name of the file, if None it will have same name as 396 saved in PumpWood. 397 if_exists: 398 Values must be in {'fail', 'change_name', 'overwrite'}. 399 Set what to do if there is a file with same name. 400 auth_header: 401 Auth header to substitute the microservice original 402 at the request (user impersonation). 403 base_filter_skip (list): 404 List of base query filter to be skiped, it is necessary to 405 be superuser to skip base query filters. 406 n_parallel (int): 407 Number of parallel requests, if None will use the default 408 one. 409 error_handler (ParallelErrorHandlerInput): 410 Forwarded to ``parallel_call``. 411 filter_errors (bool): 412 Forwarded to ``parallel_call``. Default ``True``. When 413 ``False``, return shape matches ``parallel_call``. 414 415 Returns: 416 Returns the file path that recived the file content. 417 418 Raises: 419 PumpWoodForbidden: 420 'storage_object attribute not set for view, file operations 421 are disable'. This indicates that storage for this backend 422 was not configured, so it is not possible to make storage 423 operations, 424 PumpWoodForbidden: 425 'file_field must be set on self.file_fields dictionary'. This 426 indicates that the `file_field` parameter is not listed as 427 a file field on the backend. 428 PumpWoodObjectDoesNotExist: 429 'field [{}] not found or null at object'. This indicates that 430 the file field requested is not present on object fields. 431 PumpWoodObjectDoesNotExist: 432 'Object not found in storage [{}]'. This indicates that the 433 file associated with file_field is not avaiable at the 434 storage. This should not ocorrur, it might have a manual 435 update at the model_class table or manual removal/rename of 436 files on storage. 437 """ 438 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 439 440 # Convert arguments to list 441 list_model_class = self.convert_to_list( 442 argument=model_class, length=len(list_pk)) 443 list_file_field = self.convert_to_list( 444 argument=file_field, length=len(list_pk)) 445 list_file_name = self.convert_to_list( 446 argument=file_name, length=len(list_pk)) 447 list_auth_header = self.convert_to_list( 448 argument=auth_header, length=len(list_pk)) 449 list_save_path = self.convert_to_list( 450 argument=save_path, length=len(list_pk)) 451 list_if_exists = self.convert_to_list( 452 argument=if_exists, length=len(list_pk)) 453 list_base_filter_skip = self.convert_to_list( 454 argument=base_filter_skip, length=len(list_pk), 455 force_replicate=True) 456 457 column_arg = { 458 'model_class': list_model_class, 459 'pk': list_pk, 460 'file_field': list_file_field, 461 'file_name': list_file_name, 462 'auth_header': list_auth_header, 463 'save_path': list_save_path, 464 'if_exists': list_if_exists, 465 'base_filter_skip': list_base_filter_skip, 466 } 467 function_args = self.transpose_args(dict_list=column_arg) 468 return self.parallel_call( 469 function=self.retrieve_streaming_file, function_args=function_args, 470 n_parallel=n_parallel, error_handler=error_handler, 471 filter_errors=filter_errors)
Retrieve a file from PumpWood using streaming to retrieve content.
This funcion uses file streaming to retrieve file content, it should be prefered when dealing with large (bigger than 10Mb) files transfer. Using this end-point the file is not loaded on backend memory content is transfered by chucks that are read at the storage and transfered to user.
It will necessarily save the content as a file, there is not the possibility of retrieving the content directly from request.
Arguments:
- model_class: Class of the model to retrieve file.
- list_pk (list): Pk of the object associeted file.
- file_field: Field of the file to be downloaded.
- auth_header: Dictionary containing the auth header.
- save_path: Path of the directory to save file.
- file_name: Name of the file, if None it will have same name as saved in PumpWood.
- if_exists: Values must be in {'fail', 'change_name', 'overwrite'}. Set what to do if there is a file with same name.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Returns the file path that recived the file content.
Raises:
- PumpWoodForbidden: 'storage_object attribute not set for view, file operations are disable'. This indicates that storage for this backend was not configured, so it is not possible to make storage operations,
- PumpWoodForbidden: 'file_field must be set on self.file_fields dictionary'. This
indicates that the
file_fieldparameter is not listed as a file field on the backend. - PumpWoodObjectDoesNotExist: 'field [{}] not found or null at object'. This indicates that the file field requested is not present on object fields.
- PumpWoodObjectDoesNotExist: 'Object not found in storage [{}]'. This indicates that the file associated with file_field is not avaiable at the storage. This should not ocorrur, it might have a manual update at the model_class table or manual removal/rename of files on storage.
14class ABCParallelSaveMicroservice(ABCParallelBaseMicroservice): 15 """Abstract class for parallel calls at Pumpwood end-points.""" 16 17 def parallel_save(self, list_obj_dict: list[dict], 18 files: list[dict] = None, 19 auth_header: dict = None, 20 fields: list[str] | list[list[str]] = None, 21 default_fields: bool | list[bool] = False, 22 foreign_key_fields: bool | list[bool] = False, 23 related_fields: bool | list[bool] = False, 24 base_filter_skip: list | list[list[str]] = None, 25 n_parallel: int | None = None, 26 upsert: bool | list[bool] = False, 27 disable_etl_trigger: bool | list[bool] = False, 28 error_handler: ParallelErrorHandlerInput = None, 29 filter_errors: bool = True 30 ) -> list[dict] | dict[str, list[Any]]: 31 """Save or Update a new object. 32 33 Function to save or update a new model_class object. If obj_dict['pk'] 34 is None or not defined a new object will be created. The obj 35 model class is defided at obj_dict['model_class'] and if not defined an 36 PumpWoodObjectSavingException will be raised. 37 38 If files argument is set, request will be transfered using a multipart 39 request file files mapping file key to file field on backend. 40 41 Args: 42 list_obj_dict: 43 Model data dictionary. It must have 'model_class' 44 key and if 'pk' key is not defined a new object will 45 be created, else object with pk will be updated. 46 files: 47 A dictionary of files to be added to as a multi-part 48 post request. File must be passed as a file object with read 49 bytes. 50 auth_header: 51 Auth header to substitute the microservice original 52 at the request (user impersonation). 53 fields: 54 Set the fields to be returned by the list end-point. 55 default_fields: 56 Boolean, if true and fields arguments None will return the 57 default fields set for list by the backend. 58 foreign_key_fields: 59 Return forenging key objects. It will return the fk 60 corresponding object. Ex: `created_by_id` reference to 61 a user `model_class` the correspondent to User will be 62 returned at `created_by`. 63 related_fields: 64 Return related fields objects. Related field objects are 65 objects that have a forenging key associated with this 66 model_class, results will be returned as a list of 67 dictionaries usually in a field with `_set` at end. 68 Returning related_fields consume backend resorces, use 69 carefully. 70 base_filter_skip (list): 71 List of base query filter to be skiped, it is necessary to 72 be superuser to skip base query filters. 73 n_parallel (int): 74 Number of parallel requests, if None will use the default 75 one. 76 upsert (bool): 77 Perform an upsert operation, if the object associated with the 78 pk is not found, it will be inserted on the database. 79 disable_etl_trigger (bool): 80 Disable the ETL trigger for the object. 81 error_handler (ParallelErrorHandlerInput): 82 Forwarded to ``parallel_call`` (handler validation and 83 per-task failure behavior). 84 filter_errors (bool): 85 Forwarded to ``parallel_call``. Default ``True``. When 86 ``False``, return value matches ``parallel_call`` (partition 87 dict with ``result`` and ``errors``). 88 89 Returns: 90 list[dict] | dict[str, list[Any]]: 91 Saved object payloads when ``filter_errors`` is ``True``; 92 otherwise the ``parallel_call`` partition dict. 93 94 Raises: 95 PumpWoodWrongParameters: 96 Invalid ``error_handler`` signature (forwarded from 97 ``parallel_call``). 98 PumpWoodObjectSavingException: 99 'To save an object obj_dict must have model_class defined.' 100 This indicates that the obj_dict must have key `model_class` 101 indicating model class of the object that will be 102 updated/created. 103 PumpWoodObjectDoesNotExist: 104 'Requested object {model_class}[{pk}] not found.'. This 105 indicates that the pk passed on obj_dict was not found on 106 backend database. 107 PumpWoodIntegrityError: 108 Error raised when IntegrityError is raised on database. This 109 might ocorrur when saving objects that does not respect 110 uniqueness restriction on database or other IntegrityError 111 like removal of foreign keys with related data. 112 PumpWoodObjectSavingException: 113 Return error at object validation on de-serializing the 114 object or files with unexpected extensions. 115 """ 116 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 117 118 # Not coping files because it has pointers to files... don't know 119 # how would that react 120 list_files = None 121 if files is None: 122 list_files = [None] * len(list_obj_dict) 123 else: 124 list_files = files 125 126 if len(list_files) != len(list_obj_dict): 127 msg = ( 128 "When parallel save it is necessary that, if provided, " 129 "len(files) == len(list_obj_dict)") 130 raise PumpWoodException(msg) 131 132 # Convert dataframe to list 133 if isinstance(list_obj_dict, pd.DataFrame): 134 list_obj_dict = list_obj_dict.to_dict("records") 135 136 list_auth_header = self.convert_to_list( 137 argument=auth_header, length=len(list_obj_dict)) 138 list_fields = self.convert_to_list( 139 argument=fields, length=len(list_obj_dict), 140 force_replicate=True) 141 list_default_fields = self.convert_to_list( 142 argument=default_fields, length=len(list_obj_dict)) 143 list_foreign_key_fields = self.convert_to_list( 144 argument=foreign_key_fields, length=len(list_obj_dict)) 145 list_related_fields = self.convert_to_list( 146 argument=related_fields, length=len(list_obj_dict)) 147 list_base_filter_skip = self.convert_to_list( 148 argument=base_filter_skip, length=len(list_obj_dict), 149 force_replicate=True) 150 list_upsert = self.convert_to_list( 151 argument=upsert, length=len(list_obj_dict)) 152 list_disable_etl_trigger = self.convert_to_list( 153 argument=disable_etl_trigger, length=len(list_obj_dict)) 154 155 column_arg = { 156 'obj_dict': list_obj_dict, 157 'auth_header': list_auth_header, 158 'fields': list_fields, 159 'default_fields': list_default_fields, 160 'foreign_key_fields': list_foreign_key_fields, 161 'related_fields': list_related_fields, 162 'base_filter_skip': list_base_filter_skip, 163 'files': list_files, 164 'upsert': list_upsert, 165 'disable_etl_trigger': list_disable_etl_trigger, 166 } 167 function_args = self.transpose_args(dict_list=column_arg) 168 return self.parallel_call( 169 function=self.save, function_args=function_args, 170 n_parallel=n_parallel, error_handler=error_handler, 171 filter_errors=filter_errors) 172 173 def parallel_bulk_save(self, model_class: str, 174 data_to_save: pd.DataFrame | list[dict], 175 n_parallel: int = None, chunksize: int = None, 176 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 177 auth_header: dict = None, 178 error_handler: ParallelErrorHandlerInput = 179 None, filter_errors: bool = True 180 ) -> list[Any] | dict[str, list[Any]]: 181 """Break data_to_save in many parallel bulk_save requests. 182 183 Args: 184 model_class: 185 Model class of the data that will be saved. 186 data_to_save: 187 Data that will be saved 188 chunksize: 189 Length of each parallel bulk save chunk. If not set, 190 uses ``PUMPWOOD_COMMUNICATION__PARALLEL_CHUNK_SIZE`` env 191 variable (legacy spelling supported), default 10000. 192 n_parallel: 193 Number of simultaneous requests. If not set, uses 194 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 195 (legacy spelling supported), default 4. 196 auth_header: 197 Auth header to substitute the microservice original 198 at the request (user impersonation). 199 base_filter_skip (list): 200 List of base query filter to be skiped, it is necessary to 201 be superuser to skip base query filters. 202 error_handler (ParallelErrorHandlerInput): 203 Forwarded to ``parallel_call``. 204 filter_errors (bool): 205 Forwarded to ``parallel_call``. Default ``True``. When 206 ``False``, return value matches ``parallel_call``. 207 208 Returns: 209 list[Any] | dict[str, list[Any]]: 210 ``bulk_save`` responses when ``filter_errors`` is ``True``; 211 otherwise the ``parallel_call`` partition dict. 212 """ 213 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 214 if type(data_to_save) is list: 215 data_to_save = pd.DataFrame(data_to_save) 216 217 chunksize = ( 218 PARALLEL_CHUNK_SIZE if chunksize is None else chunksize) 219 220 # Break dataframe in chunks to 221 chunks = break_in_chunks( 222 df_to_break=data_to_save, chunksize=chunksize) 223 list_model_class = self.convert_to_list( 224 argument=model_class, length=len(chunks)) 225 list_auth_header = self.convert_to_list( 226 argument=auth_header, length=len(chunks)) 227 list_base_filter_skip = self.convert_to_list( 228 argument=base_filter_skip, length=len(chunks), 229 force_replicate=True) 230 231 column_arg = { 232 'model_class': list_model_class, 233 'data_to_save': chunks, 234 'auth_header': list_auth_header, 235 'base_filter_skip': list_base_filter_skip} 236 function_args = self.transpose_args(dict_list=column_arg) 237 return self.parallel_call( 238 function=self.bulk_save, function_args=function_args, 239 n_parallel=n_parallel, error_handler=error_handler, 240 filter_errors=filter_errors)
Abstract class for parallel calls at Pumpwood end-points.
17 def parallel_save(self, list_obj_dict: list[dict], 18 files: list[dict] = None, 19 auth_header: dict = None, 20 fields: list[str] | list[list[str]] = None, 21 default_fields: bool | list[bool] = False, 22 foreign_key_fields: bool | list[bool] = False, 23 related_fields: bool | list[bool] = False, 24 base_filter_skip: list | list[list[str]] = None, 25 n_parallel: int | None = None, 26 upsert: bool | list[bool] = False, 27 disable_etl_trigger: bool | list[bool] = False, 28 error_handler: ParallelErrorHandlerInput = None, 29 filter_errors: bool = True 30 ) -> list[dict] | dict[str, list[Any]]: 31 """Save or Update a new object. 32 33 Function to save or update a new model_class object. If obj_dict['pk'] 34 is None or not defined a new object will be created. The obj 35 model class is defided at obj_dict['model_class'] and if not defined an 36 PumpWoodObjectSavingException will be raised. 37 38 If files argument is set, request will be transfered using a multipart 39 request file files mapping file key to file field on backend. 40 41 Args: 42 list_obj_dict: 43 Model data dictionary. It must have 'model_class' 44 key and if 'pk' key is not defined a new object will 45 be created, else object with pk will be updated. 46 files: 47 A dictionary of files to be added to as a multi-part 48 post request. File must be passed as a file object with read 49 bytes. 50 auth_header: 51 Auth header to substitute the microservice original 52 at the request (user impersonation). 53 fields: 54 Set the fields to be returned by the list end-point. 55 default_fields: 56 Boolean, if true and fields arguments None will return the 57 default fields set for list by the backend. 58 foreign_key_fields: 59 Return forenging key objects. It will return the fk 60 corresponding object. Ex: `created_by_id` reference to 61 a user `model_class` the correspondent to User will be 62 returned at `created_by`. 63 related_fields: 64 Return related fields objects. Related field objects are 65 objects that have a forenging key associated with this 66 model_class, results will be returned as a list of 67 dictionaries usually in a field with `_set` at end. 68 Returning related_fields consume backend resorces, use 69 carefully. 70 base_filter_skip (list): 71 List of base query filter to be skiped, it is necessary to 72 be superuser to skip base query filters. 73 n_parallel (int): 74 Number of parallel requests, if None will use the default 75 one. 76 upsert (bool): 77 Perform an upsert operation, if the object associated with the 78 pk is not found, it will be inserted on the database. 79 disable_etl_trigger (bool): 80 Disable the ETL trigger for the object. 81 error_handler (ParallelErrorHandlerInput): 82 Forwarded to ``parallel_call`` (handler validation and 83 per-task failure behavior). 84 filter_errors (bool): 85 Forwarded to ``parallel_call``. Default ``True``. When 86 ``False``, return value matches ``parallel_call`` (partition 87 dict with ``result`` and ``errors``). 88 89 Returns: 90 list[dict] | dict[str, list[Any]]: 91 Saved object payloads when ``filter_errors`` is ``True``; 92 otherwise the ``parallel_call`` partition dict. 93 94 Raises: 95 PumpWoodWrongParameters: 96 Invalid ``error_handler`` signature (forwarded from 97 ``parallel_call``). 98 PumpWoodObjectSavingException: 99 'To save an object obj_dict must have model_class defined.' 100 This indicates that the obj_dict must have key `model_class` 101 indicating model class of the object that will be 102 updated/created. 103 PumpWoodObjectDoesNotExist: 104 'Requested object {model_class}[{pk}] not found.'. This 105 indicates that the pk passed on obj_dict was not found on 106 backend database. 107 PumpWoodIntegrityError: 108 Error raised when IntegrityError is raised on database. This 109 might ocorrur when saving objects that does not respect 110 uniqueness restriction on database or other IntegrityError 111 like removal of foreign keys with related data. 112 PumpWoodObjectSavingException: 113 Return error at object validation on de-serializing the 114 object or files with unexpected extensions. 115 """ 116 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 117 118 # Not coping files because it has pointers to files... don't know 119 # how would that react 120 list_files = None 121 if files is None: 122 list_files = [None] * len(list_obj_dict) 123 else: 124 list_files = files 125 126 if len(list_files) != len(list_obj_dict): 127 msg = ( 128 "When parallel save it is necessary that, if provided, " 129 "len(files) == len(list_obj_dict)") 130 raise PumpWoodException(msg) 131 132 # Convert dataframe to list 133 if isinstance(list_obj_dict, pd.DataFrame): 134 list_obj_dict = list_obj_dict.to_dict("records") 135 136 list_auth_header = self.convert_to_list( 137 argument=auth_header, length=len(list_obj_dict)) 138 list_fields = self.convert_to_list( 139 argument=fields, length=len(list_obj_dict), 140 force_replicate=True) 141 list_default_fields = self.convert_to_list( 142 argument=default_fields, length=len(list_obj_dict)) 143 list_foreign_key_fields = self.convert_to_list( 144 argument=foreign_key_fields, length=len(list_obj_dict)) 145 list_related_fields = self.convert_to_list( 146 argument=related_fields, length=len(list_obj_dict)) 147 list_base_filter_skip = self.convert_to_list( 148 argument=base_filter_skip, length=len(list_obj_dict), 149 force_replicate=True) 150 list_upsert = self.convert_to_list( 151 argument=upsert, length=len(list_obj_dict)) 152 list_disable_etl_trigger = self.convert_to_list( 153 argument=disable_etl_trigger, length=len(list_obj_dict)) 154 155 column_arg = { 156 'obj_dict': list_obj_dict, 157 'auth_header': list_auth_header, 158 'fields': list_fields, 159 'default_fields': list_default_fields, 160 'foreign_key_fields': list_foreign_key_fields, 161 'related_fields': list_related_fields, 162 'base_filter_skip': list_base_filter_skip, 163 'files': list_files, 164 'upsert': list_upsert, 165 'disable_etl_trigger': list_disable_etl_trigger, 166 } 167 function_args = self.transpose_args(dict_list=column_arg) 168 return self.parallel_call( 169 function=self.save, function_args=function_args, 170 n_parallel=n_parallel, error_handler=error_handler, 171 filter_errors=filter_errors)
Save or Update a new object.
Function to save or update a new model_class object. If obj_dict['pk'] is None or not defined a new object will be created. The obj model class is defided at obj_dict['model_class'] and if not defined an PumpWoodObjectSavingException will be raised.
If files argument is set, request will be transfered using a multipart request file files mapping file key to file field on backend.
Arguments:
- list_obj_dict: Model data dictionary. It must have 'model_class' key and if 'pk' key is not defined a new object will be created, else object with pk will be updated.
- files: A dictionary of files to be added to as a multi-part post request. File must be passed as a file object with read bytes.
- auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- fields: Set the fields to be returned by the list end-point.
- default_fields: Boolean, if true and fields arguments None will return the default fields set for list by the backend.
- foreign_key_fields: Return forenging key objects. It will return the fk
corresponding object. Ex:
created_by_idreference to a usermodel_classthe correspondent to User will be returned atcreated_by. - related_fields: Return related fields objects. Related field objects are
objects that have a forenging key associated with this
model_class, results will be returned as a list of
dictionaries usually in a field with
_setat end. Returning related_fields consume backend resorces, use carefully. - base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- n_parallel (int): Number of parallel requests, if None will use the default one.
- upsert (bool): Perform an upsert operation, if the object associated with the pk is not found, it will be inserted on the database.
- disable_etl_trigger (bool): Disable the ETL trigger for the object.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call(handler validation and per-task failure behavior). - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return value matchesparallel_call(partition dict withresultanderrors).
Returns:
list[dict] | dict[str, list[Any]]: Saved object payloads when
filter_errorsisTrue; otherwise theparallel_callpartition dict.
Raises:
- PumpWoodWrongParameters: Invalid
error_handlersignature (forwarded fromparallel_call). - PumpWoodObjectSavingException: 'To save an object obj_dict must have model_class defined.'
This indicates that the obj_dict must have key
model_classindicating model class of the object that will be updated/created. - PumpWoodObjectDoesNotExist: 'Requested object {model_class}[{pk}] not found.'. This indicates that the pk passed on obj_dict was not found on backend database.
- PumpWoodIntegrityError: Error raised when IntegrityError is raised on database. This might ocorrur when saving objects that does not respect uniqueness restriction on database or other IntegrityError like removal of foreign keys with related data.
- PumpWoodObjectSavingException: Return error at object validation on de-serializing the object or files with unexpected extensions.
173 def parallel_bulk_save(self, model_class: str, 174 data_to_save: pd.DataFrame | list[dict], 175 n_parallel: int = None, chunksize: int = None, 176 base_filter_skip: list[str] | list[list[str]] = None, # NOQA 177 auth_header: dict = None, 178 error_handler: ParallelErrorHandlerInput = 179 None, filter_errors: bool = True 180 ) -> list[Any] | dict[str, list[Any]]: 181 """Break data_to_save in many parallel bulk_save requests. 182 183 Args: 184 model_class: 185 Model class of the data that will be saved. 186 data_to_save: 187 Data that will be saved 188 chunksize: 189 Length of each parallel bulk save chunk. If not set, 190 uses ``PUMPWOOD_COMMUNICATION__PARALLEL_CHUNK_SIZE`` env 191 variable (legacy spelling supported), default 10000. 192 n_parallel: 193 Number of simultaneous requests. If not set, uses 194 ``PUMPWOOD_COMMUNICATION__N_PARALLEL`` env variable 195 (legacy spelling supported), default 4. 196 auth_header: 197 Auth header to substitute the microservice original 198 at the request (user impersonation). 199 base_filter_skip (list): 200 List of base query filter to be skiped, it is necessary to 201 be superuser to skip base query filters. 202 error_handler (ParallelErrorHandlerInput): 203 Forwarded to ``parallel_call``. 204 filter_errors (bool): 205 Forwarded to ``parallel_call``. Default ``True``. When 206 ``False``, return value matches ``parallel_call``. 207 208 Returns: 209 list[Any] | dict[str, list[Any]]: 210 ``bulk_save`` responses when ``filter_errors`` is ``True``; 211 otherwise the ``parallel_call`` partition dict. 212 """ 213 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 214 if type(data_to_save) is list: 215 data_to_save = pd.DataFrame(data_to_save) 216 217 chunksize = ( 218 PARALLEL_CHUNK_SIZE if chunksize is None else chunksize) 219 220 # Break dataframe in chunks to 221 chunks = break_in_chunks( 222 df_to_break=data_to_save, chunksize=chunksize) 223 list_model_class = self.convert_to_list( 224 argument=model_class, length=len(chunks)) 225 list_auth_header = self.convert_to_list( 226 argument=auth_header, length=len(chunks)) 227 list_base_filter_skip = self.convert_to_list( 228 argument=base_filter_skip, length=len(chunks), 229 force_replicate=True) 230 231 column_arg = { 232 'model_class': list_model_class, 233 'data_to_save': chunks, 234 'auth_header': list_auth_header, 235 'base_filter_skip': list_base_filter_skip} 236 function_args = self.transpose_args(dict_list=column_arg) 237 return self.parallel_call( 238 function=self.bulk_save, function_args=function_args, 239 n_parallel=n_parallel, error_handler=error_handler, 240 filter_errors=filter_errors)
Break data_to_save in many parallel bulk_save requests.
Arguments:
- model_class: Model class of the data that will be saved.
- data_to_save: Data that will be saved
- chunksize: Length of each parallel bulk save chunk. If not set,
uses
PUMPWOOD_COMMUNICATION__PARALLEL_CHUNK_SIZEenv variable (legacy spelling supported), default 10000. - n_parallel: Number of simultaneous requests. If not set, uses
PUMPWOOD_COMMUNICATION__N_PARALLELenv variable (legacy spelling supported), default 4. - auth_header: Auth header to substitute the microservice original at the request (user impersonation).
- base_filter_skip (list): List of base query filter to be skiped, it is necessary to be superuser to skip base query filters.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return value matchesparallel_call.
Returns:
list[Any] | dict[str, list[Any]]:
bulk_saveresponses whenfilter_errorsisTrue; otherwise theparallel_callpartition dict.
11class ABCParallelBatchMicroservice(ABCParallelBaseMicroservice): 12 """Abstract class for parallel calls at Pumpwood end-points.""" 13 14 def parallel_pivot(self, model_class: str, 15 list_args: list[dict[str, Any]], 16 columns: None | List[str] = None, 17 format: str = 'list', 18 variables: List[str] = None, 19 fields: List[str] = None, 20 show_deleted: bool = False, 21 add_pk_column: bool = False, 22 auth_header: dict = None, 23 as_dataframe: bool = False, 24 n_parallel: int = None, 25 flat_results: bool = True, 26 error_handler: ParallelErrorHandlerInput = None, 27 filter_errors: bool = True 28 ) -> Union[List[dict], pd.DataFrame]: # NOQA 29 """Execute parallel calls for pivot end-points. 30 31 This method performs multiple calls to a pivot end-point in 32 parallel, allowing to request aggregations with different filters 33 or exclusions simultaneously. 34 35 Args: 36 model_class (str): 37 Model class of the end-point. 38 list_args (list[dict[str, Any]]): 39 A list of dictionaries containing `filter_dict` and 40 `exclude_dict` to be used in the parallel queries. 41 columns (list): 42 List of columns to group by on the pivot operation. 43 Defaults to None. 44 format (str): 45 Format of the returned data. Defaults to 'list'. 46 variables (list): 47 Variables to be used in the pivot values. Defaults to None. 48 fields (list): 49 Fields to be returned by the end-point. Defaults to None. 50 show_deleted (bool): 51 If deleted objects should be included. Defaults to False. 52 add_pk_column (bool): 53 If the primary key column should be added to the result. 54 Defaults to False. 55 auth_header (dict): 56 Authorization header to impersonate the request. 57 Defaults to None. 58 as_dataframe (bool): 59 If True, returns the results as a pandas DataFrame. 60 Defaults to False. 61 n_parallel (int): 62 Number of parallel requests. If None, uses default. 63 Defaults to None. 64 flat_results (bool): 65 If True, results will be joined into a single list or 66 DataFrame. Defaults to True. 67 error_handler (ParallelErrorHandlerInput): 68 Forwarded to ``parallel_call``. 69 filter_errors (bool): 70 Forwarded to ``parallel_call``. Default ``True``. When 71 ``False``, return shape matches ``parallel_call``. 72 73 Returns: 74 Union[List[dict], pd.DataFrame]: 75 Containing objects resulting from the pivot operation, 76 either as a list of dictionaries or a pandas DataFrame. 77 78 Raises: 79 No specific raises mapped for this execution. 80 """ 81 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 82 83 # Convert arguments to list 84 dict_list = self.expand_list_args( 85 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 86 list_model_class = self.convert_to_list( 87 argument=model_class, length=len(list_args)) 88 list_auth_header = self.convert_to_list( 89 argument=auth_header, length=len(list_args)) 90 list_fields = self.convert_to_list( 91 argument=fields, length=len(list_args), 92 force_replicate=True) 93 list_format = self.convert_to_list( 94 argument=format, length=len(list_args)) 95 list_columns = self.convert_to_list( 96 argument=columns, length=len(list_args), 97 force_replicate=True) 98 list_variables = self.convert_to_list( 99 argument=variables, length=len(list_args), 100 force_replicate=True) 101 list_show_deleted = self.convert_to_list( 102 argument=show_deleted, length=len(list_args), 103 force_replicate=True) 104 list_add_pk_column = self.convert_to_list( 105 argument=add_pk_column, length=len(list_args), 106 force_replicate=True) 107 list_as_dataframe = self.convert_to_list( 108 argument=as_dataframe, length=len(list_args), 109 force_replicate=True) 110 111 column_arg = { 112 'model_class': list_model_class, 113 'auth_header': list_auth_header, 114 'fields': list_fields, 115 'columns': list_columns, 116 'format': list_format, 117 'variables': list_variables, 118 'show_deleted': list_show_deleted, 119 'add_pk_column': list_add_pk_column, 120 "as_dataframe": list_as_dataframe} 121 column_arg.update(dict_list) 122 123 function_args = self.transpose_args(dict_list=column_arg) 124 parallel_results = self.parallel_call( 125 function=self.pivot, function_args=function_args, 126 n_parallel=n_parallel, error_handler=error_handler, 127 filter_errors=filter_errors) 128 return self.finalize_parallel_output( 129 parallel_results, flat_results=flat_results, 130 as_dataframe=as_dataframe)
Abstract class for parallel calls at Pumpwood end-points.
14 def parallel_pivot(self, model_class: str, 15 list_args: list[dict[str, Any]], 16 columns: None | List[str] = None, 17 format: str = 'list', 18 variables: List[str] = None, 19 fields: List[str] = None, 20 show_deleted: bool = False, 21 add_pk_column: bool = False, 22 auth_header: dict = None, 23 as_dataframe: bool = False, 24 n_parallel: int = None, 25 flat_results: bool = True, 26 error_handler: ParallelErrorHandlerInput = None, 27 filter_errors: bool = True 28 ) -> Union[List[dict], pd.DataFrame]: # NOQA 29 """Execute parallel calls for pivot end-points. 30 31 This method performs multiple calls to a pivot end-point in 32 parallel, allowing to request aggregations with different filters 33 or exclusions simultaneously. 34 35 Args: 36 model_class (str): 37 Model class of the end-point. 38 list_args (list[dict[str, Any]]): 39 A list of dictionaries containing `filter_dict` and 40 `exclude_dict` to be used in the parallel queries. 41 columns (list): 42 List of columns to group by on the pivot operation. 43 Defaults to None. 44 format (str): 45 Format of the returned data. Defaults to 'list'. 46 variables (list): 47 Variables to be used in the pivot values. Defaults to None. 48 fields (list): 49 Fields to be returned by the end-point. Defaults to None. 50 show_deleted (bool): 51 If deleted objects should be included. Defaults to False. 52 add_pk_column (bool): 53 If the primary key column should be added to the result. 54 Defaults to False. 55 auth_header (dict): 56 Authorization header to impersonate the request. 57 Defaults to None. 58 as_dataframe (bool): 59 If True, returns the results as a pandas DataFrame. 60 Defaults to False. 61 n_parallel (int): 62 Number of parallel requests. If None, uses default. 63 Defaults to None. 64 flat_results (bool): 65 If True, results will be joined into a single list or 66 DataFrame. Defaults to True. 67 error_handler (ParallelErrorHandlerInput): 68 Forwarded to ``parallel_call``. 69 filter_errors (bool): 70 Forwarded to ``parallel_call``. Default ``True``. When 71 ``False``, return shape matches ``parallel_call``. 72 73 Returns: 74 Union[List[dict], pd.DataFrame]: 75 Containing objects resulting from the pivot operation, 76 either as a list of dictionaries or a pandas DataFrame. 77 78 Raises: 79 No specific raises mapped for this execution. 80 """ 81 n_parallel = self.get_n_parallel(n_parallel=n_parallel) 82 83 # Convert arguments to list 84 dict_list = self.expand_list_args( 85 list_args=list_args, keys=['filter_dict', 'exclude_dict']) 86 list_model_class = self.convert_to_list( 87 argument=model_class, length=len(list_args)) 88 list_auth_header = self.convert_to_list( 89 argument=auth_header, length=len(list_args)) 90 list_fields = self.convert_to_list( 91 argument=fields, length=len(list_args), 92 force_replicate=True) 93 list_format = self.convert_to_list( 94 argument=format, length=len(list_args)) 95 list_columns = self.convert_to_list( 96 argument=columns, length=len(list_args), 97 force_replicate=True) 98 list_variables = self.convert_to_list( 99 argument=variables, length=len(list_args), 100 force_replicate=True) 101 list_show_deleted = self.convert_to_list( 102 argument=show_deleted, length=len(list_args), 103 force_replicate=True) 104 list_add_pk_column = self.convert_to_list( 105 argument=add_pk_column, length=len(list_args), 106 force_replicate=True) 107 list_as_dataframe = self.convert_to_list( 108 argument=as_dataframe, length=len(list_args), 109 force_replicate=True) 110 111 column_arg = { 112 'model_class': list_model_class, 113 'auth_header': list_auth_header, 114 'fields': list_fields, 115 'columns': list_columns, 116 'format': list_format, 117 'variables': list_variables, 118 'show_deleted': list_show_deleted, 119 'add_pk_column': list_add_pk_column, 120 "as_dataframe": list_as_dataframe} 121 column_arg.update(dict_list) 122 123 function_args = self.transpose_args(dict_list=column_arg) 124 parallel_results = self.parallel_call( 125 function=self.pivot, function_args=function_args, 126 n_parallel=n_parallel, error_handler=error_handler, 127 filter_errors=filter_errors) 128 return self.finalize_parallel_output( 129 parallel_results, flat_results=flat_results, 130 as_dataframe=as_dataframe)
Execute parallel calls for pivot end-points.
This method performs multiple calls to a pivot end-point in parallel, allowing to request aggregations with different filters or exclusions simultaneously.
Arguments:
- model_class (str): Model class of the end-point.
- list_args (list[dict[str, Any]]): A list of dictionaries containing
filter_dictandexclude_dictto be used in the parallel queries. - columns (list): List of columns to group by on the pivot operation. Defaults to None.
- format (str): Format of the returned data. Defaults to 'list'.
- variables (list): Variables to be used in the pivot values. Defaults to None.
- fields (list): Fields to be returned by the end-point. Defaults to None.
- show_deleted (bool): If deleted objects should be included. Defaults to False.
- add_pk_column (bool): If the primary key column should be added to the result. Defaults to False.
- auth_header (dict): Authorization header to impersonate the request. Defaults to None.
- as_dataframe (bool): If True, returns the results as a pandas DataFrame. Defaults to False.
- n_parallel (int): Number of parallel requests. If None, uses default. Defaults to None.
- flat_results (bool): If True, results will be joined into a single list or DataFrame. Defaults to True.
- error_handler (ParallelErrorHandlerInput): Forwarded to
parallel_call. - filter_errors (bool): Forwarded to
parallel_call. DefaultTrue. WhenFalse, return shape matchesparallel_call.
Returns:
Union[List[dict], pd.DataFrame]: Containing objects resulting from the pivot operation, either as a list of dictionaries or a pandas DataFrame.
Raises:
- No specific raises mapped for this execution.
124@dataclass(frozen=True) 125class ParallelErrorSentinel: 126 """Marks one handled failure in a ``parallel_call`` result list. 127 128 Inserted when the parallel ``error_handler`` returns ``None``: the 129 batch continues and the original task exception is stored on this 130 object. With ``filter_errors=False`` on ``parallel_call``, handled 131 failures appear as ``ParallelErrorSentinel`` instances in the 132 ``errors`` list (see ``partition_parallel_results``). 133 """ 134 135 index: int 136 """Index of the task in ``function_args``.""" 137 args: dict[str, Any] 138 """Keyword arguments passed to the failed call.""" 139 error: Exception 140 """Normalized task exception (often ``PumpWoodException``)."""
Marks one handled failure in a parallel_call result list.
Inserted when the parallel error_handler returns None: the
batch continues and the original task exception is stored on this
object. With filter_errors=False on parallel_call, handled
failures appear as ParallelErrorSentinel instances in the
errors list (see partition_parallel_results).
17class ParallelTaskErrorHandler: 18 """Validates and wraps a per-task parallel ``error_handler`` callback. 19 20 Not the HTTP ``PumpWoodMicroServiceBase.error_handler``. Instantiate 21 with a callable that accepts ``index``, ``args``, and ``error`` (by 22 name). ``parallel_call`` also accepts a bare callable and wraps it. 23 """ 24 25 def __init__(self, handler: Callable[..., Exception | None]) -> None: 26 """Wrap ``handler`` after checking its parameter names. 27 28 Args: 29 handler (Callable[..., Exception | None]): 30 Called as ``handler(index=..., args=..., error=...)``. 31 Return ``None`` for a handled failure, an ``Exception`` to 32 abort with that error, or raise to abort. 33 34 Raises: 35 PumpWoodWrongParameters: 36 If ``handler`` is not callable or lacks required parameters. 37 """ 38 self._validate_handler(handler) 39 self._handler = handler 40 41 @property 42 def handler(self) -> Callable[..., Exception | None]: 43 """Underlying callback.""" 44 return self._handler 45 46 @staticmethod 47 def _validate_handler(handler: Callable[..., Any]) -> None: 48 """Ensure ``handler`` can receive index, args, and error.""" 49 if not callable(handler): 50 msg = ( 51 "parallel error handler must be callable. " 52 "Received type [{type}]") 53 raise PumpWoodWrongParameters( 54 message=msg, 55 payload={"type": type(handler).__name__}) 56 57 sig = inspect.signature(handler) 58 has_var_kw = any( 59 p.kind == inspect.Parameter.VAR_KEYWORD 60 for p in sig.parameters.values()) 61 if has_var_kw: 62 return 63 64 names = set(sig.parameters.keys()) 65 missing = _REQUIRED_HANDLER_PARAMS - names 66 if missing: 67 msg = ( 68 "parallel error handler missing parameters: {missing}. " 69 "Required: index, args, error.") 70 raise PumpWoodWrongParameters( 71 message=msg, 72 payload={ 73 "missing": sorted(missing), 74 "received": sorted(names)}) 75 76 def __call__( 77 self, *, 78 index: int, 79 args: dict[str, Any], 80 error: Exception) -> Exception | None: 81 """Invoke the wrapped handler. 82 83 Args: 84 index (int): Task index in the parallel batch. 85 args (dict[str, Any]): Keyword arguments for that task. 86 error (Exception): Normalized failure for that task. 87 88 Returns: 89 Exception | None: 90 Whatever the wrapped handler returns (see class docstring). 91 """ 92 return self._handler(index=index, args=args, error=error)
Validates and wraps a per-task parallel error_handler callback.
Not the HTTP PumpWoodMicroServiceBase.error_handler. Instantiate
with a callable that accepts index, args, and error (by
name). parallel_call also accepts a bare callable and wraps it.
25 def __init__(self, handler: Callable[..., Exception | None]) -> None: 26 """Wrap ``handler`` after checking its parameter names. 27 28 Args: 29 handler (Callable[..., Exception | None]): 30 Called as ``handler(index=..., args=..., error=...)``. 31 Return ``None`` for a handled failure, an ``Exception`` to 32 abort with that error, or raise to abort. 33 34 Raises: 35 PumpWoodWrongParameters: 36 If ``handler`` is not callable or lacks required parameters. 37 """ 38 self._validate_handler(handler) 39 self._handler = handler
Wrap handler after checking its parameter names.
Arguments:
- handler (Callable[..., Exception | None]): Called as
handler(index=..., args=..., error=...). ReturnNonefor a handled failure, anExceptionto abort with that error, or raise to abort.
Raises:
- PumpWoodWrongParameters: If
handleris not callable or lacks required parameters.
143def is_parallel_error_sentinel(value: Any) -> bool: 144 """Return whether ``value`` is a ``ParallelErrorSentinel``.""" 145 return isinstance(value, ParallelErrorSentinel)
Return whether value is a ParallelErrorSentinel.
148def partition_parallel_results( 149 results: list[Any]) -> dict[str, list[Any]]: 150 """Split ordered ``parallel_call`` slots into successes and failures. 151 152 Args: 153 results (list[Any]): 154 One entry per task (success value or ``ParallelErrorSentinel``). 155 156 Returns: 157 dict[str, list[Any]]: 158 ``result``: success values in task order. ``errors``: list of 159 ``ParallelErrorSentinel`` objects (not converted to dicts or 160 DataFrames). 161 """ 162 successes = [] 163 errors = [] 164 for item in results: 165 if is_parallel_error_sentinel(item): 166 errors.append(item) 167 else: 168 successes.append(item) 169 return {"result": successes, "errors": errors}
Split ordered parallel_call slots into successes and failures.
Arguments:
- results (list[Any]): One entry per task (success value or
ParallelErrorSentinel).
Returns:
dict[str, list[Any]]:
result: success values in task order.errors: list ofParallelErrorSentinelobjects (not converted to dicts or DataFrames).
100def coerce_parallel_task_error_handler( 101 error_handler: ParallelErrorHandlerInput) -> ( 102 ParallelTaskErrorHandler | None): 103 """Normalize ``error_handler`` for ``parallel_call``. 104 105 Args: 106 error_handler (ParallelErrorHandlerInput): 107 ``None``, a ``ParallelTaskErrorHandler``, or a bare callable. 108 109 Returns: 110 ParallelTaskErrorHandler | None: 111 Wrapped handler, or ``None`` when no handler was given. 112 113 Raises: 114 PumpWoodWrongParameters: 115 If a bare callable fails signature validation. 116 """ 117 if error_handler is None: 118 return None 119 if isinstance(error_handler, ParallelTaskErrorHandler): 120 return error_handler 121 return ParallelTaskErrorHandler(error_handler)
Normalize error_handler for parallel_call.
Arguments:
- error_handler (ParallelErrorHandlerInput):
None, aParallelTaskErrorHandler, or a bare callable.
Returns:
ParallelTaskErrorHandler | None: Wrapped handler, or
Nonewhen no handler was given.
Raises:
- PumpWoodWrongParameters: If a bare callable fails signature validation.