-
Notifications
You must be signed in to change notification settings - Fork 6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nueva clase IoT #70
Merged
Merged
Nueva clase IoT #70
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
843d436
Added IoT class.
3fa42c5
send_batch puede recibir un DataFrame. Se añadieron pruebas unitarias…
c8a8655
send_batch returns True when success.
c1fdf40
Correcting data parameter type.
1b09c52
Renombramientos. Correcta importacion de pandas. Ejemplos de uso. Lin…
7540295
Corrigiendo comentarios.
743394f
Ejemplo de uso aparte. Se agrega el log del cambio.
13046de
Se quitó versión y fecha.
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Copyright 2022 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. | ||
# | ||
# This file is part of tc_etl_lib | ||
# | ||
# tc_etl_lib is free software: you can redistribute it and/or | ||
# modify it under the terms of the GNU Affero General Public License as | ||
# published by the Free Software Foundation, either version 3 of the | ||
# License, or (at your option) any later version. | ||
# | ||
# tc_etl_lib is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero | ||
# General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. | ||
|
||
""" | ||
Exceptions handling for Python. | ||
""" | ||
|
||
import requests | ||
from typing import Any, Optional | ||
|
||
class FetchError(Exception): | ||
""" | ||
FetchError encapsulates all parameters of an HTTP request and the erroneous response. | ||
""" | ||
|
||
response: requests.Response | ||
method: str | ||
url: str | ||
params: Optional[Any] = None | ||
headers: Optional[Any] = None | ||
body: Optional[Any] = None | ||
|
||
def __init__(self, response: requests.Response, method: str, url: str, params: Optional[Any] = None, headers: Optional[Any] = None, body: Optional[Any] = None): | ||
"""Constructor for FetchError class.""" | ||
self.response = response | ||
self.method = method | ||
self.url = url | ||
self.params = params | ||
self.headers = headers | ||
self.body = body | ||
|
||
def __str__(self) -> str: | ||
return f"Failed to {self.method} {self.url} (headers: {self.headers}, params: {self.params}, body: {self.body}): [{self.response.status_code}] {self.response.text}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Copyright 2022 Telefónica Soluciones de Informática y Comunicaciones de España, S.A.U. | ||
# | ||
# This file is part of tc_etl_lib | ||
# | ||
# tc_etl_lib is free software: you can redistribute it and/or | ||
# modify it under the terms of the GNU Affero General Public License as | ||
# published by the Free Software Foundation, either version 3 of the | ||
# License, or (at your option) any later version. | ||
# | ||
# tc_etl_lib is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero | ||
# General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with IoT orchestrator. If not, see http://www.gnu.org/licenses/. | ||
|
||
''' | ||
IoT Agent routines for Python: | ||
- iotaManager.send_http | ||
- iotaManager.send_batch_http | ||
''' | ||
|
||
from . import exceptions | ||
import pandas as pd | ||
import requests | ||
import tc_etl_lib as tc | ||
import time | ||
from typing import Iterable, Optional, Union | ||
|
||
class SendBatchError(Exception): | ||
"SendBatchError is a class that can handle exceptions." | ||
def __init__(self, message, original_exception=None, index=None): | ||
super().__init__(message) | ||
self.original_exception = original_exception | ||
self.index = index | ||
|
||
class iotaManager: | ||
"""IoT Agent Manager. | ||
|
||
endpoint: define service endpoint iota (example: https://<service>:<port>). | ||
sensor_id: sensor ID. | ||
api_key: API key of the corresponding sensor. | ||
sleep_send_batch: time sleep in seconds (default: 0). | ||
""" | ||
|
||
endpoint: str | ||
sensor_id: str | ||
api_key: str | ||
sleep_send_batch: float | ||
|
||
def __init__(self, endpoint: str, sensor_id: str, api_key: str, sleep_send_batch: float = 0): | ||
self.endpoint = endpoint | ||
self.sensor_id = sensor_id | ||
self.api_key = api_key | ||
self.sleep_send_batch = sleep_send_batch | ||
|
||
def send_http(self, | ||
data: dict) -> Union[None, bool]: | ||
|
||
if not isinstance(data, dict): | ||
raise TypeError("The 'data' parameter should be a dictionary with key-value pairs.") | ||
|
||
params = { | ||
'i': self.sensor_id, | ||
'k': self.api_key | ||
} | ||
headers = { | ||
"Content-Type": "application/json" | ||
} | ||
|
||
try: | ||
resp = requests.post(url=self.endpoint, json=data, params=params, headers=headers) | ||
if resp.status_code == 200: | ||
return True | ||
else: | ||
raise exceptions.FetchError( | ||
response=resp, | ||
method="POST", | ||
url=self.endpoint, | ||
params=params, | ||
headers=headers) | ||
except requests.exceptions.ConnectionError as e: | ||
raise e | ||
|
||
def send_batch_http(self, data: Iterable) -> Union[None, bool]: | ||
|
||
if isinstance(data, pd.DataFrame): | ||
# Convert each row of the DataFrame to a dictionary. | ||
for i, row in data.iterrows(): | ||
try: | ||
self.send_http(row.to_dict()) | ||
time.sleep(self.sleep_send_batch) | ||
except Exception as e: | ||
raise SendBatchError(f"send_batch_http error. Row that caused the error: {i}\nError detail: {str(e)}", original_exception=e, index=i) from e | ||
else: | ||
for i, dictionary in enumerate(data): | ||
try: | ||
self.send_http(dictionary) | ||
time.sleep(self.sleep_send_batch) | ||
except Exception as e: | ||
raise SendBatchError(f"send_batch_http error. Index where the error occurred: {i}\nError detail: {str(e)}", original_exception=e, index=i) from e | ||
return True |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Incluir en el changelog (justo por encima de la marca de versión 0.9.0) un par de entradas que describan los cambios incluidos en esta PR. Por ejemplo: