Skip to content
Snippets Groups Projects
Commit 92d1e269 authored by Rodrigo Goncalves's avatar Rodrigo Goncalves Committed by Guilherme Arthur Gerônimo
Browse files

Support for logging requests and responses in client

parent b899546e
No related branches found
No related tags found
1 merge request!20Resolve "Data ingress for context information for tiki-wiki"
...@@ -5,16 +5,27 @@ import requests ...@@ -5,16 +5,27 @@ import requests
import json import json
class SmartDataContextAPIClient: class SmartDataContextAPIClient:
def __init__(self, cert_file, key_file, url="https://iot.lisha.ufsc.br/", verifyCertificate=True): def __init__(self, cert_file, key_file, url="https://iot.lisha.ufsc.br/", verifyCertificate=True, logfile=None):
if not url.endswith('/'): if not url.endswith('/'):
url += '/' url += '/'
self._url = url self._url = url
self._client = requests.Session() self._client = requests.Session()
self._client.cert = (cert_file, key_file) self._client.cert = (cert_file, key_file)
self._client.verify = verifyCertificate self._client.verify = verifyCertificate
self._logfile = logfile
if not verifyCertificate: if not verifyCertificate:
requests.urllib3.disable_warnings() requests.urllib3.disable_warnings()
def _log_request(self, method, url, headers, request_body, response_body):
if self._logfile:
with open(self._logfile, 'a') as log_file:
log_file.write(f"URL: {method} {url}\n")
log_file.write(f"Headers: {json.dumps(headers, indent=2)}\n")
if request_body:
log_file.write(f"Request Body: {json.dumps(request_body, indent=2)}\n")
log_file.write(f"Response Body: {response_body}\n")
log_file.write("\n" + "-"*50 + "\n")
def _doJsonPost(self, json_data, return_attribute = '', endpoint="api/v1_1/context.php"): def _doJsonPost(self, json_data, return_attribute = '', endpoint="api/v1_1/context.php"):
headers = { headers = {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
...@@ -23,6 +34,7 @@ class SmartDataContextAPIClient: ...@@ -23,6 +34,7 @@ class SmartDataContextAPIClient:
response = self._client.post(url, headers=headers, json=json_data) response = self._client.post(url, headers=headers, json=json_data)
try: try:
response_json = response.json() response_json = response.json()
self._log_request("POST", url, headers, json_data, response.json())
if "errors" in response_json: if "errors" in response_json:
raise Exception(f"Error processing request: {json.dumps(response_json['errors'])}") raise Exception(f"Error processing request: {json.dumps(response_json['errors'])}")
else: else:
...@@ -157,6 +169,7 @@ class SmartDataContextAPIClient: ...@@ -157,6 +169,7 @@ class SmartDataContextAPIClient:
response = self._client.post(url, headers=headers, data=data) response = self._client.post(url, headers=headers, data=data)
try: try:
response_json = response.json() response_json = response.json()
self._log_request("POST", url, headers, {"data": "binary data"}, response.json())
if "errors" in response_json: if "errors" in response_json:
raise Exception(f"Error processing request: {json.dumps(response_json['errors'])}") raise Exception(f"Error processing request: {json.dumps(response_json['errors'])}")
else: else:
...@@ -177,6 +190,7 @@ class SmartDataContextAPIClient: ...@@ -177,6 +190,7 @@ class SmartDataContextAPIClient:
} }
response = self._client.post(url, headers=headers, json=json_request) response = self._client.post(url, headers=headers, json=json_request)
try: try:
self._log_request("POST", url, dict(response.headers), json_request, "")
response.raise_for_status() response.raise_for_status()
return response.content return response.content
except Exception as e: except Exception as e:
......
...@@ -16,7 +16,8 @@ def generate_random_file(filename, size_in_mb): ...@@ -16,7 +16,8 @@ def generate_random_file(filename, size_in_mb):
# Create a new SmartDataContextClient, passing a custom URL for the API and the certificates to access the domain # Create a new SmartDataContextClient, passing a custom URL for the API and the certificates to access the domain
# The parameter verifyCertificate allows using self-signed certificates for development and test environments. # The parameter verifyCertificate allows using self-signed certificates for development and test environments.
# Should not be used in production ideally # Should not be used in production ideally
client = SmartDataContextAPIClient(cert_file=CLIENT_CERTIFICATE, key_file=CLIENT_CERTIFICATE_KEY, url=API_URL, verifyCertificate=False) client = SmartDataContextAPIClient(cert_file=CLIENT_CERTIFICATE, key_file=CLIENT_CERTIFICATE_KEY, url=API_URL, verifyCertificate=False,
logfile="requests.log")
# Creates a new perene SmartDataContext (no start not end time). The minimum required parameters are the content # Creates a new perene SmartDataContext (no start not end time). The minimum required parameters are the content
# and the features, with at least one feature (tags), which indicate tags to be associated with this SmartDataContext # and the features, with at least one feature (tags), which indicate tags to be associated with this SmartDataContext
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment