spade_artifact.common.readers package
Submodules
spade_artifact.common.readers.apireader module
- class spade_artifact.common.readers.apireader.APIReaderArtifact(jid, passwd, api_url, data_processor=None, http_method='GET', params=None, headers=None, time_request=None)[source]
Bases:
ArtifactAn artifact for asynchronously reading and processing data from an API endpoint.
This artifact sends HTTP requests to a specified API URL and processes the response data. It supports customizable HTTP methods, parameters, and headers. The processed data is then published at regular intervals.
- Attributes:
api_url (str): The URL of the API endpoint to send requests to. data_processor (Callable): A function that processes the data received from the API. It takes the response data as input and returns a list of messages to be published. http_method (str, optional): The HTTP method to use for the request (e.g., ‘GET’, ‘POST’). Defaults to ‘GET’. params (dict, optional): A dictionary of parameters to be sent in the query string of the request. Defaults to an empty dictionary. headers (dict, optional): A dictionary of HTTP headers to send with the request. Defaults to an empty dictionary. time_request(int, optional) : Time in minutes to wait for the request data update.
- Args:
jid (str): The JID (Jabber Identifier) of the artifact. passwd (str): The password for the artifact to authenticate with the XMPP server. api_url (str): The URL of the API endpoint to send requests to. data_processor (Callable): The function that will process the data received from the API. http_method (str, optional): The HTTP method to use for the request. Defaults to ‘GET’. params (dict, optional): Parameters to include in the request. Defaults to None, which is converted to an empty dictionary. headers (dict, optional): HTTP headers to include in the request. Defaults to None, which is converted to an empty dictionary. time_request(int, optional) : Time in minutes to wait for the request data update.
- async static default_data_processor(data)[source]
Default data processor function that passes the data through without any transformation.
- Args:
data: The data received from the API request.
- Returns:
A list containing the original data.
- async run()[source]
Starts the artifact’s main operation of sending requests to the API and processing the responses.
This method sends an HTTP request to the specified API URL using the specified method, parameters, and headers. The response is then processed using the data_processor function, and the processed data is published at regular intervals.
spade_artifact.common.readers.context_broker_inserter module
- class spade_artifact.common.readers.context_broker_inserter.InserterArtifact(jid, passwd, publisher_jid, host, project_name, columns_update=[], data_processor=None, json_template=None, json_exceptions=None, port='9090')[source]
Bases:
ArtifactAn artifact for inserting and updating data in an Orion Context Broker.
This class facilitates communication with an Orion Context Broker instance, allowing for the creation and update of entities based on received payloads. It utilizes an asynchronous queue to manage incoming data and ensures that data is sent to the context broker in a timely manner.
- Attributes:
api_url (str): The URL of the Orion Context Broker API. headers (dict): Headers used for HTTP requests to the Orion Context Broker. columns_update (list): A list of columns to update. If empty, all columns are updated. data_processor (Callable): Function to process the data received from the artifact. json_template (dict): Template for constructing JSON payloads. json_exceptions (dict): Exceptions for JSON cleaning rules.
- artifact_callback(artifact: str, payload: str)[source]
Callback function triggered when data is received from the linked artifact.
This function processes the received payload using the data processor and puts the processed data into the payload queue.
- Args:
artifact (str): The name or identifier of the artifact sending the data. payload (str): The JSON payload received from the artifact.
- Raises:
json.JSONDecodeError: If the payload is not valid JSON.
- build_entity_json(payload, clean=True)[source]
Constructs the JSON structure for an Orion entity based on the received payload and a template.
- Args:
payload (dict): The payload received from the publisher artifact. clean (bool): Whether to clean the result by removing entries without ‘value’ or ‘type’.
- Returns:
dict: A dictionary representing the JSON structure of the Orion entity.
- async create_new_entity(entity_data: dict)[source]
Creates a new entity in the Orion Context Broker.
This function sends a POST request to the Orion Context Broker to create a new entity with the provided data.
- Args:
entity_data (dict): The data for the new entity.
- Raises:
Exception: If the HTTP request fails or the entity creation is unsuccessful.
- static default_data_processor(data: dict) list[source]
Default data processor function that passes the data through without any transformation.
This function serves as the default data processor, which simply returns the data encapsulated in a list without performing any modifications.
- Args:
data (dict): The data received from the API request.
- Returns:
list: A list containing the original data.
- async entity_exists(entity_id: str) bool[source]
Checks if an entity exists in the Orion Context Broker.
This function sends a GET request to the Orion Context Broker to check if an entity with the specified ID exists.
- Args:
entity_id (str): The ID of the entity to check.
- Returns:
bool: True if the entity exists, False otherwise.
- Raises:
Exception: If the HTTP request fails.
- async process_and_send_data(payload: dict)[source]
Processes the given payload and sends the data to the Orion Context Broker.
This function constructs the entity ID and JSON data, checks if the entity exists, and either updates the existing entity’s attributes or creates a new entity.
- Args:
payload (dict): The payload containing data to be sent to the Orion Context Broker.
- Raises:
KeyError: If ‘type’ or ‘id’ keys are missing in the payload.
- async run()[source]
Continuously processes and sends data from the payload queue to the Orion Context Broker.
This function sets the presence to available and enters an infinite loop where it waits for data from the payload queue, processes it, and sends it to the Orion Context Broker.
- Raises:
Exception: If processing or sending data fails.
- async setup()[source]
Sets up the InserterArtifact by making it available and linking it to the publisher artifact.
This method sets the presence to available, waits for a second, and then links the artifact to the publisher using the provided publisher_jid. If the linking fails, it logs an error.
- Raises:
Exception: If linking to the publisher fails.
- async update_all_attributes(entity_id, entity_data, context)[source]
Updates all attributes of an existing entity in the Orion Context Broker.
This function sends a PATCH request to the Orion Context Broker to update each attribute of an entity with the provided data. If any attribute does not exist, it uses a POST request to add it.
- Args:
entity_id (str): The ID of the entity to update. entity_data (dict): The data to update the entity with. context (any): The JSON-LD context to include in the payload.
- Raises:
Exception: If the HTTP request fails or the attribute update is unsuccessful.
- async update_entity_attribute(entity_id: str, attribute: str, attribute_data: dict, context: any)[source]
Updates a specific attribute of an existing entity in the Orion Context Broker.
This function sends a PATCH request to the Orion Context Broker to update a specific attribute of an entity with the provided data. If the attribute does not exist, it uses a POST request to add it.
- Args:
entity_id (str): The ID of the entity to update. attribute (str): The attribute of the entity to update. attribute_data (dict): The data to update the attribute with. context (any): The JSON-LD context to include in the payload.
- Raises:
Exception: If the HTTP request fails or the attribute update is unsuccessful.
- async update_or_create_entity(entity_id: str, entity_data: dict, payload: dict)[source]
Updates all attributes of an existing entity or creates a new entity if it does not exist.
- Args:
entity_id (str): The ID of the entity to update or create. entity_data (dict): The data to update or create the entity with.
spade_artifact.common.readers.csvreader module
- class spade_artifact.common.readers.csvreader.CSVReaderArtifact(jid, passwd, csv_file, columns=None, frequency=1, time_column=None)[source]
Bases:
ArtifactAn artifact for asynchronously reading and processing data from CSV files.
This artifact reads data from a CSV file and publishes each row at regular intervals or based on a time column.
- Attributes:
csv_file (str): Path to the CSV file to be read. columns (list[str], optional): A list of column names to read from the CSV file. If None, all columns are read. frequency (int, optional): The frequency in seconds at which rows are published if no time_column is specified. Defaults to 1. time_column (str, optional): The name of the column that contains timestamp information. If specified, rows are published based on the time difference between rows instead of the fixed frequency.
- Args:
jid (str): The JID (Jabber Identifier) of the artifact. passwd (str): The password for the artifact to authenticate with the XMPP server. csv_file (str): Path to the CSV file to be read. columns (list[str], optional): A list of column names to read from the CSV file. Defaults to None. frequency (int, optional): The frequency in seconds at which rows are published if no time_column is specified. Defaults to 1. time_column (str, optional): The name of the column that contains timestamp information.
- async run()[source]
Starts the artifact’s main operation of reading from the CSV and publishing rows.
This method reads the CSV file row by row, and if a time_column is specified, it waits for the time difference between the current and last row before publishing the next row. If no time_column is specified, it publishes rows at a fixed frequency defined by the frequency attribute.
spade_artifact.common.readers.mongodbreader module
- class spade_artifact.common.readers.mongodbreader.MongoDBQueryArtifact(connection_uri, database_name, collection_name, operation, query, jid, password, data_processor=None, time_request=None)[source]
Bases:
ArtifactAn enhanced artifact for executing various MongoDB operations and processing the results.
This class supports performing a wide range of database operations on MongoDB, such as find, insert, update, and delete. It also allows for processing the results and performing actions at regular intervals.
- Attributes:
connection_uri (str): MongoDB connection URI. database_name (str): Name of the MongoDB database. collection_name (str): Name of the MongoDB collection. operation (str): Type of MongoDB operation to be performed. This attribute supports the following operations:
‘find’: Retrieves documents from the collection that match the criteria specified in query. The query
should be a dictionary representing the MongoDB query.
‘insert’: Inserts a new document into the collection. The query should contain the document to be inserted.
‘update’: Updates documents in the collection that match the criteria. The query should be a dictionary
with ‘filter’ and ‘update’ keys, where ‘filter’ defines the criteria to identify documents to be updated, and ‘update’ specifies the modifications.
‘delete’: Deletes documents from the collection that match the criteria specified in query. The query
should be a dictionary representing the MongoDB deletion criteria.
query (dict): The MongoDB query or document for operations. data_processor (Callable): A function to process the data received from the operation. time_request (int, optional): Time in seconds to wait before re-executing the operation.
- Args:
connection_uri (str): MongoDB connection URI. database_name (str): Name of the MongoDB database. collection_name (str): Name of the MongoDB collection. operation (str): Type of MongoDB operation. query (dict): The MongoDB query or document. jid (str): JID for the spade artifact. password (str): Password for the spade artifact. data_processor (Callable, optional): Function to process the operation results. Defaults to None. time_request (int, optional): Time in seconds for the operation re-execution interval. Defaults to None.
- async connect_to_database()[source]
Asynchronously establishes a connection to the MongoDB database.
- static default_data_processor(data)[source]
Default data processor function that passes the data through without any transformation.
- Args:
data: The data received from the API request.
- Returns:
A list containing the original data.
- async execute_operation()[source]
Asynchronously executes the specified MongoDB operation and fetches the results.
This method supports various operations like find, insert, update, and delete. The operation to be performed is determined by self.operation.
- Returns:
The data fetched or affected by executing the specified operation.
- async run()[source]
Asynchronously and periodically executes the MongoDB query based on self.time_request.
After each iteration, the method waits for self.time_request seconds before the next execution. When the loop ends, it ensures that the client connection to MongoDB is properly closed to release resources.
spade_artifact.common.readers.sqlreader module
- class spade_artifact.common.readers.sqlreader.DatabaseQueryArtifact(jid, password, db_type, connection_params, query, data_processor=None, time_request=None)[source]
Bases:
ArtifactAn artifact for executing and processing database queries.
This class supports executing database queries either on SQL or PostgreSQL databases, processing the results, and performing actions at regular intervals.
- Attributes:
- db_type (str): The type of the database. This parameter accepts the following values:
‘mysql’: Indicates that the database is a MySQL database. Requires pymysql library.
‘sqlite’: Indicates that the database is a SQLite database. Uses Python’s built-in sqlite3 library.
‘postgresql’: Indicates that the database is a PostgreSQL database. Requires psycopg library.
- connection_params (dict): Details required to connect to the database. The structure of this dictionary varies based on the db_type:
- For ‘mysql’ and ‘postgresql’: This dictionary should include the following keys:
‘host’: The hostname or IP address of the database server.
‘user’: The username used to authenticate with the database.
‘password’: The password used to authenticate with the database.
‘database’: The name of the database to connect to.
Additionally, for ‘postgresql’, the key ‘port’ can be included to specify the database server port.
- For ‘sqlite’: This dictionary needs only one key:
‘database’: The file path of the SQLite database. If the file does
query (str): The database query to be executed. data_processor (Callable): A function to process the data received from the query. time_request (int, optional): Time in seconds to wait before re-executing the query.
- Args:
db_type (str): The type of the database. connection_params (dict): Connection details for the database. query (str): The database query. data_processor (Callable, optional): Function to process the query results. Defaults to None. time_request (int, optional): Time in seconds for the query re-execution interval. Defaults to None.
- async connect_to_database()[source]
Asynchronously establishes a connection to the database using the appropriate library based on db_type.
- Raises:
ValueError: If db_type is not supported.
- static default_data_processor(data)[source]
Default data processor function that passes the data through without any transformation.
- Args:
data: The data received from the API request.
- Returns:
A list containing the original data.
- async execute_query()[source]
Asynchronously executes the database query and fetches the results.
Ensures a database connection is established, then executes the query stored in self.query, fetches all results, and processes them using self.data_processor.
- Returns:
The data fetched from executing self.query.
- prepare_connection_string()[source]
Prepares the database connection string or parameters based on the database type after validating them. Returns:
The connection string for PostgreSQL, a dictionary of parameters for MySQL, or the database filename for SQLite.
- Raises:
ValueError: If there are issues with the connection parameters or the database type is not supported.
- async run()[source]
Asynchronously and periodically executes the database query based on self.time_request.
After each iteration, the method waits for self.time_request seconds before the next execution. When the loop ends, it ensures that the cursor and the database connection are properly closed to release resources.