Due to a scheduled upgrade to version 14.10, GitLab will be unavailabe on Monday 30.05., from 19:00 until 20:00.

Commit 1424b5b7 authored by Jonas Waeber's avatar Jonas Waeber
Browse files

Refactor WriteTypeReportToDrupal.py

Fix bug where url was wrong.
parent 5d1dcfe0
Pipeline #26229 passed with stages
in 2 minutes and 2 seconds
...@@ -6,6 +6,15 @@ import json ...@@ -6,6 +6,15 @@ import json
class WriteTypeReportToDrupal(Resource): class WriteTypeReportToDrupal(Resource):
def __init__(self):
self.base_url = current_app.config["drupal-api-url"]
self.headers = {
'Content-Type': 'application/vnd.api+json',
'Accept': 'application/vnd.api+json',
'X-API-Key': current_app.config['drupal-api-key']
}
def post(self): def post(self):
""" """
Write a report for an recordset or institution Drupal Write a report for an recordset or institution Drupal
...@@ -55,8 +64,8 @@ class WriteTypeReportToDrupal(Resource): ...@@ -55,8 +64,8 @@ class WriteTypeReportToDrupal(Resource):
'message': f'Missing a element in input body: {er}' 'message': f'Missing a element in input body: {er}'
}, 400 }, 400
try: try:
node_id = get_node_id(identifier, node_type) node_id = self.get_node_id(identifier, node_type)
return write_results(node_type, node_id, status, report) return self.write_results(node_type, node_id, status, report)
except ImportApiError as e: except ImportApiError as e:
current_app.logger.error( current_app.logger.error(
f"Could not write report to {node_type}/{identifier}: {e.message}") f"Could not write report to {node_type}/{identifier}: {e.message}")
...@@ -64,90 +73,77 @@ class WriteTypeReportToDrupal(Resource): ...@@ -64,90 +73,77 @@ class WriteTypeReportToDrupal(Resource):
'error': f"Could not write report to {node_type}/{identifier}: " 'error': f"Could not write report to {node_type}/{identifier}: "
f"{e.message}"}, 500 f"{e.message}"}, 500
def get_node_id(self, memobase_id: str, node_type: str):
current_app.logger.debug(
f'Retrieve node id from durpal json api with memobase id {memobase_id}.')
url = f'{self.base_url}/jsonapi/node/{node_type}?filter[' \
f'field_memobase_id]={memobase_id}'
def get_node_id(memobase_id: str, node_type: str): response = requests.get(url, headers=self.headers)
current_app.logger.debug( if response.ok:
f'Retrieve node id from durpal json api with memobase id {memobase_id}.') try:
headers = { return response.json()['data'][0]['attributes']['drupal_internal__nid']
'Content-Type': 'application/vnd.api+json', except KeyError as er:
'Accept': 'application/vnd.api+json', current_app.logger.error(f"Could not find the key {er} in data: {response.text}.")
'X-API-Key': current_app.config['drupal-api-key'] raise ImportApiError(f"Could not find the key {er} in data (url={url}): "
}
url = f'{current_app.config["drupal-api-url"]}/jsonapi/node/{node_type}?filter['\
f'field_memobase_id]={memobase_id}'
response = requests.get(url, headers=headers)
if response.ok:
try:
return response.json()['data'][0]['attributes']['drupal_internal__nid']
except KeyError as er:
current_app.logger.error(f"Could not find the key {er} in data: {response.text}.")
raise ImportApiError(f"Could not find the key {er} in data (url={url}): "
f"{response.text}.")
except IndexError:
current_app.logger.error(f"Data field does not contain a list (url={url}): "
f"{response.text}.") f"{response.text}.")
raise ImportApiError(f"Data field does not contain a list (url={url}): " except IndexError:
f"{response.text}.") current_app.logger.error(f"Data field does not contain a list (url={url}): "
else: f"{response.text}.")
raise ImportApiError(f"Could not find element for report: {response.text}.") raise ImportApiError(f"Data field does not contain a list (url={url}): "
f"{response.text}.")
else:
raise ImportApiError(f"Could not find element for report: {response.text}.")
def write_results(node_type, identifier, status, report): def write_results(self, node_type, identifier, status, report):
current_app.logger.debug( current_app.logger.debug(
"writing: " + node_type + "/" + str(identifier) + "/" + str(status) + "/" + report) "writing: " + node_type + "/" + str(identifier) + "/" + str(status) + "/" + report)
headers = {
'Content-Type': 'application/vnd.api+json',
'Accept': 'application/vnd.api+json',
'X-API-Key': current_app.config['drupal-api-key']
}
drupal_type = '' drupal_type = ''
url = f'{current_app.config["drupal-api-url"]}/jsonapi/node/{identifier}' url = f'{self.base_url}/jsonapi/node/'
if node_type == 'institution': if node_type == 'institution':
drupal_type = 'node--institution' drupal_type = 'node--institution'
url += 'institution/' url += 'institution/'
elif node_type == 'recordset': elif node_type == 'recordset':
drupal_type = 'node--record_set' drupal_type = 'node--record_set'
url += 'record_set/' url += 'record_set/'
url += identifier url = f'{url}{identifier}'
data = { data = {
"data": { "data": {
"type": drupal_type, "type": drupal_type,
"attributes": { "attributes": {
"field_migrated": status, "field_migrated": status,
"field_error": report "field_error": report
}
} }
} }
}
result = {'message': ''} result = {'message': ''}
try: try:
response = requests.patch( response = requests.patch(
url, url,
headers=headers, headers=self.headers,
data=json.dumps(data) data=json.dumps(data)
) )
except requests.exceptions.RequestException: except requests.exceptions.RequestException:
message = "It was not possible to write to Drupal API \ message = f'Request Error: {url}'
via the following url " + url current_app.logger.error(message)
current_app.logger.error(message) raise ImportApiError(message)
raise ImportApiError(message) if response.ok:
if response.ok: current_app.logger.debug('Updated: ' + url)
current_app.logger.debug('Updated: ' + url) result['message'] += 'Updated: ' + url + '\n'
result['message'] += 'Updated: ' + url + '\n' elif response.status_code == 403:
elif response.status_code == 403: message = f"Authorization Failed: {url}"
message = "Not authorized to write to: " + url current_app.logger.error(message)
current_app.logger.error(message) raise ImportApiError(message)
raise ImportApiError(message) elif response.status_code == 404:
elif response.status_code == 404: message = 'Not Found: ' + url
message = 'Not Found: ' + url current_app.logger.error(message)
current_app.logger.error(message) raise ImportApiError(message)
raise ImportApiError(message) else:
else: message = "Unknown response status code for drupal api for url " + url
message = "Unknown response status code for drupal api for url " + url current_app.logger.error(message)
current_app.logger.error(message) raise ImportApiError(message)
raise ImportApiError(message) return result
return result
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment