To initialize the client using a token_jwt with a .env file.
Create a .env file with the following content: TOKEN_JWT="token_jwt"
Load the environment variable and initialize the client:
client = OpenGateClient()
By default, if you use OpenGateClient without parameters, and you set the environment variable TOKEN_JWT, OpenGateClient will be created with this value. If you want to use TOKEN_JWT from environment, you may delete the OPENGATE_API_KEY environment variable.
Basic use with environment variables
The most professional way to initialize the client is by using standard environment variables. If you set these, you can simply call OpenGateClient():
Basic use of token_jwt with an environment variable
To initialize the client using a token_jwt from an environment variable, you can set the token_jwt directly in your environment without relying on a .env:
Create environment variable
On UNIX systems, use:
export TOKEN_JWT="token_jwt"
On Windows, use:
set TOKEN_JWT="token_jwt"
Initialize the client.
client = OpenGateClient()
Similar to the previous example, if you use OpenGateClient without parameters, and you set the environment variable TOKEN_JWT, OpenGateClient will be created with this value. If you want to use TOKEN_JWT from environment, you may delete API_KEY variable environment.
Basic use without url for services K8s
To initialize the OpenGateClient without specifying a URL, you can either omit the url parameter or set it to None.
Similar to the previous examples, you have the option to provide the api_key directly, set it to None, or omit it altogether. If you choose to omit it, the client will automatically retrieve the api_key from the environment variable if it is set. Additionally, you can also authenticate using a username and password by specifying those credentials instead.
Features
The library consists of the following modules:
IA
Models
Pipelines
Transformers
Collection
Collection
Bulk Collection
Pandas Collection
Provision
Asset
Bulk
Devices
Processor
Rules
Rules
Searching
Alarms
Datapoints
Data sets
Entities
Operations
Rules
Timeseries
File Connector
File Connector
Basic Examples of the OpenGate-Data Modules
The unit tests double as usage examples: opengate_data/test/unit/ holds one
directory per module, each showing the configurations and use cases of its
builders.
License
This project is licensed under the Apache License 2.0.
This method allows you to specify the path where the output file will be saved.
It is particularly useful for operations that involve downloading or saving files.
Arguments:
output_file_pathstr - The path where the output file will be saved.
Returns:
AIModelsBuilder - The instance of the AIModelsBuilder class.
Example:
builder.with_output_file_path("rute/prueba.onnx")
create
defcreate() ->"AIModelsBuilder"
Initiates the creation process of a new model.
This method prepares the AIModelsBuilder instance to create a new model by setting up the necessary parameters such as the organization name and the file to be associated with the model.
Returns:
AIModelsBuilder - The instance of the AIModelsBuilder class itself, allowing for method chaining.
This method sets up the AIModelsBuilder instance to make a prediction using a specific model associated with the specified organization and identifier.
Returns:
AIModelsBuilder - The instance of the AIModelsBuilder class itself, allowing for method chaining.
Selects the operation that writes the model identifier into a
configuration file.
It stores the identifier given to with_identifier() under the section
and key named with with_config_file(), so a later run can pick the
model up from the file instead of carrying its identifier in the code.
The key must already exist in the file.
Returns:
AIModelsBuilder - Returns itself to allow for method chaining.
Selects the operation that writes the model identifier into the .env
file.
It stores the identifier given to with_identifier() under the variable
named with with_env(), so a later run can pick the model up from the
environment. The variable must already exist in the .env file.
Returns:
AIModelsBuilder - Returns itself to allow for method chaining.
Raises:
ValueError - If the variable is not in the .env file.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
AIModelsBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> Response
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
AIPipelinesBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Notes:
This method should be used as a final step before execute to prepare the operations search configuration. It does not modify the state but ensures that the builder’s state is ready for execution.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
create
defcreate() ->"AIPipelinesBuilder"
Creates a new pipeline.
This method prepares the request to create a new pipeline using the specified configuration in the object. It is necessary to define the name (with_name) and actions (add_action) before calling this method.
Returns:
AIPipelinesBuilder - Returns the same object to allow method chaining.
This method prepares the request to find a specific pipeline based on its identifier. The identifier is obtained automatically if not explicitly defined or can be obtained from a configuration file or environment variables.
Returns:
AIPipelinesBuilder - Returns the same object to allow method chaining.
This method prepares the request to update an existing pipeline. It is necessary to define the organization’s name (with_organization_name) and the pipeline’s name (with_name) before calling this method.
Returns:
AIPipelinesBuilder - Returns the same object to allow method chaining.
This method prepares the request to delete an existing pipeline. It is necessary to define the organization’s name (with_organization_name) and the pipeline’s identifier (with_identifier) before calling this method.
Returns:
AIPipelinesBuilder - Returns the same object to allow method chaining.
This method prepares the request to perform a prediction using the model associated with the specified pipeline. It is necessary to define the organization’s name (with_organization_name), the pipeline’s identifier (with_identifier), and provide prediction data (with_prediction) before calling this method.
Returns:
AIPipelinesBuilder - Returns the same object to allow method chaining.
This method sets up the AIPipelinesBuilder instance to save the configuration of a model associated with the specified organization. It configures the URL endpoint for the save operation and sets the operation type to ‘save’.
Returns:
AIPipelinesBuilder - The instance of the AIModelsBuilder class itself, allowing for method chaining.
Selects the operation that writes the pipeline identifier into a
configuration file.
It stores the identifier given to with_identifier() under the section
and key named with with_config_file(), so a later run can pick the
pipeline up from the file instead of carrying its identifier in the code.
The key must already exist in the file.
Returns:
AIPipelinesBuilder - Returns itself to allow for method chaining.
Selects the operation that writes the pipeline identifier into the
.env file.
It stores the identifier given to with_identifier() under the variable
named with with_env(), so a later run can pick the pipeline up from the
environment. The variable must already exist in the .env file.
Returns:
AIPipelinesBuilder - Returns itself to allow for method chaining.
Raises:
ValueError - If the variable is not in the .env file.
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
This method allows specifying one or more files to be included in the transformer resource being created. The content type for each file can be specified if needed.
Arguments:
file_pathstr - Full path to the file to add.
filetypestr, optional - Content type of the file. Defaults to None, meaning the content type will be automatically inferred.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
This method allows you to specify the path where the output file will be saved.
It is particularly useful for operations that involve downloading or saving files.
Arguments:
output_file_pathstr - The path where the output file will be saved.
Returns:
AITransformersBuilder - The instance of the AIModelsBuilder class.
This method allows you to specify the name of the file that will be used in operations such as download or evaluation. It is particularly useful when working with specific files that require unique identifiers or names for processing.
Arguments:
file_namestr - The name of the file to be processed.
Returns:
AITransformersBuilder - Returns self for chaining.
Example:
builder.with_file_name('pkl_encoder.pkl')
create
defcreate() ->"AITransformersBuilder"
Prepares the creation of the transformer resource.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
Searches for a single transformer resource by its identifier.
This method prepares the request to find a specific transformer based on its identifier. The identifier is obtained automatically if not explicitly defined or can be obtained from a configuration file or environment variables.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
This method prepares the URL and HTTP method necessary to send a PUT request to the API to update an existing transformer. It is necessary to configure the relevant attributes of the AITransformersBuilder instance, including the identifier of the transformer to update, before calling this method.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
This method prepares the URL and HTTP method necessary to send a DELETE request to the API to delete an existing transformer. It is necessary to configure the identifier attribute of the AITransformersBuilder instance before calling this method.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
This method sets up the AIModelsBuilder instance to download the file of a specific model associated with the specified organization and identifier. It configures the URL endpoint for the download operation and sets the operation type to ‘download’.
Returns:
AITransformersBuilder - The instance of the AIModelsBuilder class itself, allowing for method chaining.
Prepares the evaluation of the transformer with provided data.
This method sets up the URL and method for evaluating the transformer using the provided data. The evaluation data should be set using the with_evaluate method before calling this method.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
This method prepares the URL and method for saving the transformer configuration. It checks if the identifier is set from the environment or configuration file and then either updates or creates the transformer accordingly.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
Sets the transformer identifier in the configuration file.
This method sets the transformer identifier in the specified configuration file. It reads the configuration file, updates the identifier, and writes the changes back to the file.
Returns:
AITransformersBuilder - Returns the current instance to allow method chaining.
Selects the operation that writes the transformer identifier into the
.env file.
It stores the identifier held by the builder under the variable named
with with_env(), so a later run can pick the transformer up from the
environment. The variable must already exist in the .env file.
Returns:
AITransformersBuilder - Returns itself to allow for method chaining.
Raises:
ValueError - If the variable is not in the .env file.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
AITransformersBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> requests.Response
Sends the selected operation to the platform.
Which request goes out depends on the operation chosen in the chain:
create, find, update, delete, download, evaluate, save, or resolving the
identifier from a configuration file or from the environment.
Returns:
requests.Response | dict | str: Whatever the selected operation
produces — the transformer payload, the contents of a downloaded
file, or a dict carrying status_code and either data or error.
Raises:
ValueError - If no operation was selected in the chain.
Multiple datastreams can be grouped under a single identifier
Arguments:
device_idstr - The identifier of the device the datapoints belong to.
datastream_idstr - The identifier for the datastream to which the datapoints will be added.
datapointslist[tuple[int | float | bool | dict | list, None | datetime | int, None | datetime | int]] - A list of tuples where each tuple
represents a datapoint. Each tuple contains the datapoint value and an optional timestamp (‘at’):
value - Collected value
at - Number with the time in miliseconds from epoch of the measurement. If this field is None, the platform will assign the server current time to the datapoint whe data is received.
feedstr | None - The feed to collect the datapoints under. Optional.
Returns:
IotBulkCollectionBuilder - Returns itself to allow for method chaining.
Multiple datastreams can be grouped under a single identifier
Arguments:
device_idstr - The identifier of the device the datapoints belong to.
datastream_idstr - The identifier for the datastream to which the datapoints will be added.
datapointslist[tuple[int | float | bool | dict, None | datetime | int, None | datetime | int]] - A list of tuples where each tuple
represents a datapoint. Each tuple contains the datapoint value and an optional timestamp (‘at’) (‘from):
value - Collected value
at - Number with the time in miliseconds from epoch of the measurement. If this field is None, the platform will assign the server current time to the datapoint whe data is received.
from - Number with the time in miliseconds from epoch of the start period of measurement. This indicates that value is the same within this time interval (from, at).
feedstr | None - The feed to collect the datapoints under. Optional.
Returns:
IotBulkCollectionBuilder - Returns itself to allow for method chaining.
Processes a DataFrame to extract device, data and datapoints, and adds them to the payload.
Arguments:
dfpd.DataFrame - The DataFrame containing the device data and datapoints. The DataFrame
is expected to have columns that match the expected structure for device
datastreams and datapoints.
Returns:
IotBulkCollectionBuilder - Returns itself to allow for method chaining.
deffrom_spreadsheet(
path: str, sheet_name_index: int | str) ->"IotBulkCollectionBuilder"
Loads data from a spreadsheet, processes it, and adds the resulting device data and datapoints
to the payload. This method is particularly useful for bulk data operations where data is
stored in spreadsheet format.
Arguments:
pathstr - The file path to the spreadsheet to load.
sheet_name_indexint | str - The sheet name or index to load from the spreadsheet.
Returns:
IotBulkCollectionBuilder - Returns itself to allow for method chaining.
Finalizes the construction of the entities search configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
IotBulkCollectionBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute(include_payload=False)
This method is a shortcut that combines building and executing in a single step.
Arguments:
include_payloadbool - Whether the response should carry the payload that was sent. Defaults to False.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
This method is used to retrieve the entire payload that has been constructed by the builder. The payload
includes all devices, their respective datastreams, and the datapoints that have been added to each datastream.
This is particularly useful for inspecting the current state of the payload after all configurations and
additions have been made, but before any execution actions (like sending data to a server) are taken.
Returns:
dict - A dictionary representing the current state of the payload within the IotBulkCollectionBuilder.
This dictionary includes all devices, datastreams, and datapoints that have been configured.
Raises:
Exception - If the build method was not called before this method.
Example:
builder.to_dict()
execute
defexecute(include_payload=False)
Executes the IoT collection based on the current configuration of the builder.
Arguments:
include_payloadbool - Determine if the payload should be included in the response.
Returns:
dict - A dictionary containing the results of the execution, including success messages for each device ID
if the data was successfully sent, or error messages detailing what went wrong.
Raises:
Exception - If build() has not been called before execute(), or if it was not the last method invoked prior to execute().
Indicates that a validation of the Trusted_boot type is required, it is not necessary to enter the value of the field but if you enter it,
the entire message received by the platform will compare the value of TrustedBoot with the provisioned value, if they are different
the message will not be collected.
Add the trustedboot to the constructor and validates the type.
Arguments:
trustedbootstr - The unique identifier for the device.
Returns:
IotCollectionBuilder - Returns itself to allow for method chaining.
Multiple datastreams can be grouped under a single identifier
Arguments:
datastream_idstr - The identifier for the datastream to which the datapoints will be added.
datapointslist[tuple[int | float | bool | dict | list, None | datetime | int, None | datetime | int]] - A list of tuples where each tuple
represents a datapoint. Each tuple contains the datapoint value and an optional timestamp (‘at’):
value - Collected value
at - Number with the time in miliseconds from epoch of the measurement. If this field is None, the platform will assign the server current time to the datapoint whe data is received.
feedstr | None - The feed to collect the datapoints under. Optional.
Returns:
IotCollectionBuilder - Returns itself to allow for method chaining.
Multiple datastreams can be grouped under a single identifier
Arguments:
datastream_idstr - The identifier for the datastream to which the datapoints will be added.
datapointslist[tuple[int | float | bool | dict, None | datetime | int, None | datetime | int]] - A list of tuples where each tuple
represents a datapoint. Each tuple contains the datapoint value and an optional timestamp (‘at’) (‘from):
value - Collected value
at - Number with the time in miliseconds from epoch of the measurement. If this field is None, the platform will assign the server current time to the datapoint whe data is received.
from - Number with the time in miliseconds from epoch of the start period of measurement. This indicates that value is the same within this time interval (from, at).
feedstr | None - The feed to collect the datapoints under. Optional.
Returns:
IotCollectionBuilder - Returns itself to allow for method chaining.
Constructs the collection configuration from a dictionary input.
This method dynamically applies builder methods based on the keys in the input dictionary. It should be used after the build() method has been called to ensure that the builder is in a proper state to accept configuration from a dictionary.
Arguments:
payloaddict[str, Any] - The dictionary containing the configuration Args.
Returns:
IotCollectionBuilder - Returns itself to allow for method chaining.
Raises:
ValueError - If required keys are missing in the payload or if the ‘datastreams’ field is empty.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
IotCollectionBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Notes:
This method should be used as a final step before execute to prepare the IoT collection configuration. It does not modify the state but ensures that the builder’s state is ready for execution.
Example:
builder.build()
to_dict
defto_dict() -> dict
This method is used to retrieve the entire payload that has been constructed by the builder. The payload
includes all devices, their respective datastreams, and the datapoints that have been added to each datastream.
This is particularly useful for inspecting the current state of the payload after all configurations and
additions have been made, but before any execution actions (like sending data to a server) are taken.
Returns:
dict - A dictionary representing the current state of the payload within the IotCollectionBuilder.
This dictionary includes all devices, datastreams, and datapoints that have been configured.
Raises:
Exception - If the build() method was not called before this method.
Example:
builder.build().to_dict()
build_execute
defbuild_execute(include_payload: bool =False)
Executes the IoT collection immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step. It should be used when you want to build and execute the configuration without modifying the builder state in between these operations.
It first validates the build configuration and then executes the collection if the validation is successful.
Arguments:
include_payloadbool - Determine if the payload should be included in the response.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance, indicating that build_execute is being incorrectly used after build.
Exception - If there are issues during the execution process, including network or API errors.
Executes the IoT collection based on the current configuration of the builder.
Arguments:
include_payloadbool - Determine if the payload should be included in the response.
Returns:
Dict - A dictionary containing the execution response which includes the status code and,
optionally, the payload. If an error occurs, a string describing the error is returned.
Raises:
Exception - If build() has not been called before execute(), or if it was not the last method invoked prior to execute().
Set the input DataFrame that contains the IoT data to process.
The DataFrame must include a ‘device_id’ and ‘at’ column. Additional columns are considered
as potential datastream values. If ‘at’ is empty or None, a timestamp will be assigned.
Arguments:
dfpd.DataFrame - The DataFrame with ‘device_id’ and ‘at’ columns.
Returns:
PandasIotCollectionBuilder - The current builder instance.
Raises:
Exception - If ‘device_id’ or ‘at’ column is missing in the DataFrame.
Specify the columns from the DataFrame that should be included as datastreams in the IoT payload.
If this method is not called, all available datastream columns (except required/optional ones) are used.
If it is called, only the specified columns will be considered.
Arguments:
columnslist[str] - The list of column names to include as datastreams.
Returns:
PandasIotCollectionBuilder - The current builder instance.
Raises:
Exception - If any specified column does not exist in the DataFrame.
Set the maximum number of bytes per request for IoT collection.
This controls how the payload is batched when sending to the endpoint.
Arguments:
max_bytesint - The maximum request size in bytes.
Returns:
PandasIotCollectionBuilder - The current builder instance.
build
defbuild() ->"PandasIotCollectionBuilder"
Build the request payload after the DataFrame and columns have been configured.
This method processes the DataFrame, converting columns into the appropriate IoT datastream format.
It must be called before execute() if not using build_execute().
Returns:
PandasIotCollectionBuilder - The current builder instance.
Raises:
Exception - If build() and build_execute() are used together.
Execute the request after building it with build() or build_execute().
If include_payload is True, it returns a JSON string with the payload and results.
Otherwise, it returns a pandas DataFrame with a status column summarizing the results.
Arguments:
include_payloadbool - Whether to include the payload in the result. Defaults to False.
Returns:
Union[str, pd.DataFrame]: The result of the IoT collection request.
Raises:
Exception - If the required method invocation order is not respected.
Reads a value from the INI and saves it as a source. ‘prefer’ controls whether the value will be interpreted as identifier, name, or auto (first id, then name).
Arguments:
config_filestr - Path to the INI file to read.
sectionstr - The section of the INI file the value lives in.
config_keystr - The key holding the value.
preferstr - How to read the value: ‘identifier’, ’name’, or ‘auto’ to try the identifier first and fall back to the name. Defaults to ‘auto’.
Searches for a single dataset resource by its identifier.
This method prepares the request to find a specific dataset based on its identifier. The identifier is obtained automatically if not explicitly defined or can be obtained from a configuration file or environment variables.
Returns:
FindDatasetsBuilder - Returns the current instance to allow method chaining.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
FindDatasetsBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> Response
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
The provided list can include one or more filesystem paths. They will be
appended to the same internal collection used by add_local_file, so you
can freely combine both methods:
NOTE: if you mix from_dataframe with setters in download (path/filenames/output_path),
then you must use all THREE setters; if not, use only from_dataframe.
Arguments:
dfpandas.DataFrame - The DataFrame holding the files to upload.
defaultsdict | None - Values to fall back on when a row leaves a
column out: “destiny_path”, “path”, “overwrite” and “output_path”.
upload
defupload() ->"FileConnectorBuilder"
Configures the builder to upload a file to the specified organization.
This method sets the internal state of the builder to prepare for a file upload operation. It does not execute the operation immediately but prepares the necessary configurations for when the execute method is called.
Returns:
FileConnectorBuilder - Returns itself to allow for method chaining.
Example:
builder.upload()
list_all
deflist_all() ->"FileConnectorBuilder"
Configures the builder to list files available in the specified organization.
This method sets the internal state of the builder to prepare for a file listing operation. It does not execute the operation immediately but prepares the necessary configurations for when the execute method is called.
Returns:
FileConnectorBuilder - Returns itself to allow for method chaining.
Example:
builder.list_all()
list_one
deflist_one() ->"FileConnectorBuilder"
Configures the builder to list a single file from the specified organization.
This method sets the internal state of the builder to prepare for a single file listing operation. It does not execute the operation immediately but prepares the necessary configurations for when the execute method is called.
Returns:
FileConnectorBuilder - Returns itself to allow for method chaining.
Example:
builder.list_one()
download
defdownload() ->"FileConnectorBuilder"
Configures the builder to download a file from the specified organization.
This method sets the internal state of the builder to prepare for a file download operation. It does not execute the operation immediately but prepares the necessary configurations for when the execute method is called.
Returns:
FileConnectorBuilder - Returns itself to allow for method chaining.
Example:
builder.download()
delete
defdelete() ->"FileConnectorBuilder"
Selects the operation that deletes files from the file connector.
Requires with_destiny_path(). Name the files to remove with
add_remote_file() or add_remote_multiple_files(); with none named,
the whole path is deleted.
Returns:
FileConnectorBuilder - Returns itself to allow for method chaining.
Sends the selected operation to the file connector.
Which request goes out depends on the operation chosen in the chain:
upload(), list_all(), list_one(), download() or delete(). The
two listing operations default to the “dict” format when
with_format() was not called.
Returns:
requests.Response | dict | str | pandas.DataFrame: The listing in
the requested format, the contents of a download, or a dict carrying
status_code and either data or error.
Raises:
RuntimeError - If build() was not the last call before execute(),
or if neither build() nor build_execute() was called.
ValueError - If no operation was selected in the chain.
This method sets up the ProvisionDeviceBuilder instance to update a specific device associated with the specified organization and identifier.
You can update a device with a flattened format sending a PUT request using the URL above. You must replace {identifier} with the identifier of the device you want to update. Also, it is sent a boolean parameter, flattened, to allow sending a flattened JSON format
Returns:
ProvisionDeviceBuilder - The instance of the ProvisionDeviceBuilder class itself, allowing for method chaining.
Finalizes the construction of the device configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
ProvisionDeviceBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> str | dict[str, str | int]
Execute the configured device and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Example:
builder.execute()
opengate_data.provision.devices
opengate_data.provision.bulk.provision_bulk
ProvisionBulkBuilder Objects
classProvisionBulkBuilder()
Provision Bulk Builder
Provisions many entities in a single request, which is the way to go when a
per-entity call would mean thousands of them. The payload can come from a
file — from_json(), from_csv(), from_excel() — or from memory, with
from_dataframe() or from_dict().
with_bulk_action() chooses what to do with the rows — CREATE by default,
UPDATE, PATCH or DELETE — and with_bulk_type() what they are, ENTITIES by
default or TICKETS. Close the chain with build() and execute(), or with
build_execute().
Finalizes the construction of the provision bulk configuration.
This method prepares the builder to execute the request by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the request to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the organization name are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
ProvisionBulkBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute(include_payload=False)
Executes the provision bulk immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step. It should be used when you want to build and execute the configuration without modifying the builder state in between these operations.
It first validates the build configuration and then executes the request if the validation is successful.
Arguments:
include_payloadbool - Determine if the payload should be included in the response.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance, indicating that build_execute is being incorrectly used after build.
Exception - If there are issues during the execution process, including network or API errors.
Example:
response = builder.build_execute()
execute
defexecute(include_payload=False)
Executes the provision bulk based on the current configuration of the builder.
Arguments:
include_payloadbool - Determine if the payload should be included in the response.
Returns:
Dict - A dictionary containing the execution response which includes the status code and,
optionally, the payload. If an error occurs, a string describing the error is returned.
Raises:
Exception - If build() has not been called before execute(), or if it was not the last method invoked prior to execute().
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
ProvisionProcessorBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> requests.Response
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Example:
builder.build_execute()
opengate_data.provision.asset.provision_asset
ProvisionAssetBuilder Objects
classProvisionAssetBuilder()
Provision Asset Builder
Provisions assets: creates them, reads one, updates and deletes. Describe
the asset with the with_provision_* setters and
add_provision_datastream_value(), or hand over a whole payload with
from_dict() or from_dataframe(). Then pick the operation — create(),
find_one(), update(), delete() — and close the chain with build()
and execute(), or with build_execute().
This method sets up the ProvisionAssetBuilder instance to update a specific asset associated with the specified organization and identifier.
You can update an asset with a flattened format sending a PUT request using the URL above. You must replace {identifier} with the identifier of the asset you want to update. Also, it is sent a boolean parameter, flattened, to allow sending a flattened JSON format
Returns:
ProvisionAssetBuilder - The instance of the ProvisionAssetBuilder class itself, allowing for method chaining.
This method sets up the ProvisionAssetBuilder instance to update a specific asset associated with the specified organization and identifier.
You can update an asset with a flattened format sending a Patch request using the URL above. You must replace {identifier} with the identifier of the asset you want to update. Also, it is sent a boolean parameter, flattened, to allow sending a flattened JSON format
Returns:
ProvisionAssetBuilder - The instance of the ProvisionAssetBuilder class itself, allowing for method chaining.
Finalizes the construction of the asset configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
ProvisionAssetBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> str | dict[str, str | int]
Execute the configured asset and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Waiting threshold before actions are executed. Allows cancellation of the execution of actions if another rule exists with a subsequent delay cancellation action.
Specify the condition for the rule.
Mandatory for EASY mode and not applicable for ADVANCED mode.
JSON filter which follows the same filter structure of the Opengate platform.
It can contain rule parameters.
Arguments:
conditiondict - Specify the identifier for the rule.
This method prepares the RulesBuilder instance to create a new model by setting up the necessary parameters such as the organization name and the file to be associated with the model. It also specifies the URL endpoint for creating the model and sets the operation type to ‘create’.
Returns:
RulesBuilder - The instance of the RulesBuilder class itself, allowing for method chaining.
This method sets up the RulesBuilder instance to delete a specific model associated with the specified organization and identifier. It configures the URL endpoint for the delete operation and sets the operation type to ‘delete’.
Returns:
RulesBuilder - The instance of the RulesBuilder class itself, allowing for method chaining.
This function prepares the RulesBuilder instance to retrieve the catalog of rules
Returns:
RulesBuilder - The RulesBuilder instance itself, allowing method chaining.
Example:
builder.catalog()
save
defsave() ->"RulesBuilder"
Selects the create-or-update operation.
It reads the rule identifier from the .env variable set with
with_env(), or from the file set with with_config_file(), and then
decides on its own: if a rule with that identifier already exists it is
updated, and if it does not, it is created and the resulting identifier
written back to the same place. Use it when a script has to be safe to
run more than once.
Returns:
RulesBuilder - Returns itself to allow for method chaining.
Selects the operation that writes the rule identifier into a
configuration file.
It stores the identifier given to with_identifier() under the section
and key named with with_config_file(), so a later run can pick the rule
up from the file instead of carrying its identifier in the code. The key
must already exist in the file.
Returns:
RulesBuilder - Returns itself to allow for method chaining.
Selects the operation that writes the rule identifier into the .env
file.
It stores the identifier given to with_identifier() under the variable
named with with_env(), so a later run can pick the rule up from the
environment. The variable must already exist in the .env file.
Returns:
RulesBuilder - Returns itself to allow for method chaining.
Raises:
ValueError - If there is no identifier to write, or if the variable
is not in the .env file.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
RulesBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the data sets search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute()
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Example:
builder.execute()
opengate_data.rules
Searching
opengate_data.searching.filter
FilterBuilder Objects
classFilterBuilder(Expressions)
Filter Builder
and_
defand_(*conditions)
Combines conditions using the logical AND operator.
Arguments:
*conditions - The conditions to combine.
Returns:
FilterBuilder - Returns itself to allow for method chaining.
Searches the alarms raised by the platform’s rules, over
/v80/search/entities/alarms. Compose the query with the inherited
with_filter, with_select, with_limit and with_format methods, then
close it with build() and execute(), or with build_execute().
The value must be the identifier of one of the sorts declared in the
dataset definition “sorts” section (the auto-generated reverse sorts are
also valid). When omitted, results are sorted by the identifier column
ascending.
The sort is sent in the payload for every format. NOTE: the platform
currently ignores the sort for ‘csv’ and ‘pandas’ exports (a
server/database limitation, not an SDK decision); it is still sent so
the SDK stays forward-compatible if the backend starts honoring it.
Arguments:
sortstr - The sort identifier declared in the dataset definition.
Returns:
DatasetsSearchBuilder - Returns itself to allow for method chaining.
Deprecated for datasets. The dataset search API no longer accepts the
object-based sort format; sorts are now declared in the dataset
definition and referenced by identifier.
Raises:
NotImplementedError - Always. Use with_sort() instead.
execute
defexecute()
Executes the data set search based on the built configuration.
Returns:
dict, csv or dataframe: The response data in the specified format.
Raises:
Exception - If the build() method was not called before execute().
This function allows the data returned by the search to be transposed, meaning that rows and columns are swapped. This can be useful for certain data analyses where it is preferred to have datastreams as columns and entities as rows.
Notes:
This function can only be used with the ‘pandas’ format.
Returns:
DataPointsSearchBuilder - Returns the builder instance to allow for method chaining.
Enables transposing the data with a specific mapping.
This function allows the data returned by the search
to be transposed and mapped according to a provided mapping dictionary.
The mapping specifies how complex data should be transformed into flat columns.
Arguments:
mappingdict[str, dict[str, str]] - The mapping of complex data to flat
columns. The main key is the column name, and its value another
dictionary defining the mapping of the substructures.
Notes:
This function can only be used with the ‘pandas’ format.
Returns:
DataPointsSearchBuilder - Returns the builder instance to allow for method chaining.
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern.
It ensures that the build method has been called and that it is the last method invoked before execute.
Depending on the configured method (e.g., create, find, update, delete),
it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception:
If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Exports the data of a timeseries to a file — Parquet unless you ask for
another content type — and reports the state of an export already running.
Both operations work over the same endpoint,
/v80/timeseries/provision/organizations/{organization}/{identifier}/export:
export() starts one with a POST, export_status() asks about it with a
GET.
Pick the operation, then close the chain with build() and execute(), or
with build_execute(). Only one export per timeseries can run at a time.
To read rows instead of exporting them, use
client.new_timeseries_search_builder().
Not supported for the Parquet export. The export endpoint decides the
output order internally and cannot be changed, and any ‘sort’ field in
the payload makes the platform reject the request as “Json is malformed”.
To read timeseries data in a given order, use the search builder instead:
client.new_timeseries_search_builder().with_sort(""),
where the identifier is one of the sorts declared in the timeseries
definition (or its automatically exposed reverse). Note that sorting is
also disabled server-side for CSV output.
Raises:
NotImplementedError - Always.
export
defexport() ->"TimeseriesBuilder"
Selects the operation that starts an export of the timeseries data.
Returns:
TimeseriesBuilder - Returns itself to allow for method chaining.
dict[str, Any]: Always carries status_code, plus data on success
or error with the response body on failure. For export(), 202
means the export was accepted and runs in the background, 204 that
the timeseries holds no data, and 409 that another process is
already exporting it. For export_status(), 200 carries the parsed
state of the export; a 406 is retried for up to 20 seconds before
being returned.
Raises:
Exception - If build() or build_execute() was not called first.
Reads a value from the INI and saves it as a source. ‘prefer’ controls whether the value will be interpreted as identifier, name, or auto (first id, then name).
Arguments:
config_filestr - Path to the INI file to read.
sectionstr - The section of the INI file the value lives in.
config_keystr - The key holding the value.
preferstr - How to read the value: ‘identifier’, ’name’, or ‘auto’ to try the identifier first and fall back to the name. Defaults to ‘auto’.
Searches for a single timeseries resource by its identifier.
This method prepares the request to find a specific timeseries based on its identifier. The identifier is obtained automatically if not explicitly defined or can be obtained from a configuration file or environment variables.
Returns:
FindTimeseriesBuilder - Returns the current instance to allow method chaining.
Finalizes the construction of the IoT collection configuration.
This method prepares the builder to execute the collection by ensuring all necessary configurations are set and validates the overall integrity of the build. It should be called before executing the collection to ensure that the configuration is complete and valid.
The build process involves checking that mandatory fields such as the device identifier are set. It also ensures that method calls that are incompatible with each other (like build and build_execute) are not both used.
Returns:
FindTimeseriesBuilder - Returns itself to allow for method chaining, enabling further actions like execute.
Raises:
ValueError - If required configurations are missing or if incompatible methods are used together.
Example:
builder.build()
build_execute
defbuild_execute()
Executes the timeseries search immediately after building the configuration.
This method is a shortcut that combines building and executing in a single step.
Returns:
dict - A dictionary containing the execution response which includes the status code and potentially other metadata about the execution.
Raises:
ValueError - If build has already been called on this builder instance.
Example:
builder.build_execute()
execute
defexecute() -> Response
Execute the configured operation and return the response.
This method executes the operation that has been configured using the builder pattern. It ensures that the build method has been called and that it is the last method invoked before execute. Depending on the configured method (e.g., create, find, update, delete), it calls the appropriate internal execution method.
Returns:
requests.Response - The response object from the executed request.
Raises:
Exception - If the build method has not been called or if it is not the last method invoked before execute.
ValueError - If the configured method is unsupported.
Example:
builder.execute()
opengate_data.timeseries
Utils
opengate_data.utils.expressions
Expressions Objects
classExpressions()
Expressions
The filter conditions a search accepts, as static methods returning plain
dicts: eq, neq, like, gt, lt, gte, lte, in_, nin and
exists. FilterBuilder extends this class, so in practice you reach them
through client.new_filter_builder() and combine them with and_ / or_
before calling build().
Validates that the given variable is of the expected type or types.
This function checks if the variable matches the expected type or any type in a tuple of expected types.
It raises a TypeError if the variable does not match the expected type(s).
Arguments:
variableAny - The variable to be checked.
expected_typeAny - The expected type or a tuple of expected types.
variable_namestr - The name of the variable, used in the error message to identify the variable.
Raises:
TypeError - If the variable is not of the expected type(s).
Returns:
None - This function does not return a value; it raises an exception if the type check fails.
set_method_call
defset_method_call(method)
Decorates a method to ensure it is properly registered and tracked within the builder’s workflow.
This decorator adds the method’s name to a set that tracks method calls
Arguments:
methodfunction - The method to be decorated.
Returns:
function - The wrapped method with added functionality to register its call.
Raises:
None - This decorator does not raise exceptions by itself but ensures the method call is registered.
parse_json
defparse_json(value)
Attempts to convert a string into a Python object by interpreting it as JSON.
Arguments:
valuestr | Any - The value to attempt to convert. If the value is not a string,
it is returned directly without attempting conversion.
Returns:
Any - The Python object resulting from the JSON conversion if value is a valid JSON string.
If the conversion fails due to a formatting error (ValueError), the original value is returned.
If value is not a string, it is returned as is.
This function processes the HTTP response and returns a dictionary containing the status code. If the response indicates an error, it also includes the error message.
Arguments:
responserequests.Response - The response object to process.
Returns:
dict[str, Any]: A dictionary containing the status code and, if applicable, the error message.
Turn a failed HTTP response into the dictionary the builders return.
Nothing is raised: the caller gets the status code and, when the platform
sent one, the body as the error.
Arguments:
responserequests.Response - The response object to process.
Returns:
dict[str, Any]: The status code and, if the response carried a body,
the error.
handle_exception
defhandle_exception(e)
Turn a transport failure into the dictionary the builders return.
A request that never reached the platform has no status code, so the
result names the kind of failure instead: connection, timeout, request or
unexpected.
Arguments:
eException - The exception raised while sending the request.
Returns:
dict[str, str]: The kind of failure and its details.
Check that a chain was closed properly before execute() runs.
Every builder has to be closed with build() or with build_execute(),
and build() has to be the last call before execute() — otherwise a
setter called after it would never be validated.
Arguments:
method_callslist[str] - The methods called on the builder, in order.
Raises:
Exception - If build() was called more than once, if it was not the
last call before execute(), or if neither build() nor
build_execute() was called.
Generic builder validator with messages intended for the end user.
The two alias maps exist so the errors name what the caller wrote, not the
internals: without them a missing with_destiny_path() would be reported
as a missing ‘path’.
Arguments:
methodstr - The operation selected in the chain, which picks its
entry in the spec.
statedict - The current value of each field of the builder, by
internal name.
specdict - The rules per operation: ‘required’ and ‘forbidden’ field
names, ‘choices’ mapping a field to its allowed values, and
‘custom’ holding extra checks called with the state.
used_methodslist[str] | None - The methods called on the builder, in
order. Needed to catch two operations in the same chain.
allowed_method_callsset[str] | None - The method names that select an
operation, of which a chain may use exactly one, once.
field_aliasesdict[str, str] | None - Maps internal fields to public
setter names (e.g., ‘path’ → ‘with_path’).
method_aliasesdict[str, str] | None - Maps logical method names to
public method names (e.g., ’list_one’ → ’list_one()’).
Raises:
RuntimeError - If the chain combines several operations, or repeats one.
ValueError - If no operation was selected, if it is not in the spec, or
if the state misses a required field, carries a forbidden one, or
holds a value outside its choices.