Skip to content
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

Wrap external calls with try-except #67

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions healthtools/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,14 @@ def __call__(self, req):
req = super(AWS4AuthNotUnicode, self).__call__(req)
req.headers = {str(name): value for name, value in req.headers.items()}
return req

def print_error(message):
'''
Print error messages in the terminal.
'''
error = "- ERROR: " + message['ERROR']
source = ("- SOURCE: " + message['SOURCE']) if "SOURCE" in message else ""
error_msg = "- MESSAGE: " + message['MESSAGE']
msg = "\n".join([error, source, error_msg])

log.error(msg)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably able to be achieved with formatting? - https://docs.python.org/3/howto/logging-cookbook.html

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trying it out.

24 changes: 16 additions & 8 deletions healthtools/search/elastic.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
from healthtools.core import es, es_index
from healthtools.core import es, es_index, print_error


def search(query, doc_type):
result = es.search(
index=es_index,
body={'query': match_all_text(query)},
doc_type=doc_type
)
hits = result.get('hits', {})
return hits
try:
result = es.search(
index=es_index,
body={'query': match_all_text(query)},
doc_type=doc_type
)
hits = result.get('hits', {})
return hits
except Exception as err:
error = {
"ERROR": "Elastic Search",
"MESSAGE": str(err)
}
print_error(error)



def match_all():
Expand Down
41 changes: 24 additions & 17 deletions healthtools/search/nurses.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import requests
from bs4 import BeautifulSoup
from healthtools.core import print_error


NURSING_COUNCIL_URL = 'http://nckenya.com/services/search.php?p=1&s={}'
Expand All @@ -16,26 +17,32 @@ def get_nurses_from_nc_registry(query):
Get nurses from the nursing council of Kenya registry
'''
url = NURSING_COUNCIL_URL.format(query)
response = requests.get(url)
nurses = {'hits': [], 'total': 0}
try:
response = requests.get(url)
if 'No results' in response.content:
return nurses

if 'No results' in response.content:
return nurses

# make soup for parsing out of response and get the table
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'zebra'}).find('tbody')
rows = table.find_all("tr")
# make soup for parsing out of response and get the table
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'zebra'}).find('tbody')
rows = table.find_all("tr")

# parse table for the nurses data
for row in rows:
# only the columns we want
columns = row.find_all('td')[:len(NURSES_FIELDS)]
columns = [text.text.strip() for text in columns]
# parse table for the nurses data
for row in rows:
# only the columns we want
columns = row.find_all('td')[:len(NURSES_FIELDS)]
columns = [text.text.strip() for text in columns]

entry = dict(zip(NURSES_FIELDS, columns))
nurses['hits'].append(entry)
entry = dict(zip(NURSES_FIELDS, columns))
nurses['hits'].append(entry)

nurses['total'] = len(nurses['hits'])
nurses['total'] = len(nurses['hits'])

return nurses
return nurses
except Exception as err:
error = {
"ERROR": "get_nurses_from_nc_registry()",
"MESSAGE": str(err)
}
print_error(error)
6 changes: 6 additions & 0 deletions healthtools/search/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from healthtools.settings import WIT_ACCESS_TOKEN

from healthtools.documents import DOCUMENTS, doc_exists
from healthtools.core import print_error

from healthtools.search import elastic, nurses

Expand Down Expand Up @@ -55,6 +56,11 @@ def determine_doc_type(query, doc_type=None):
for keyword in DOCUMENTS[doc]['keywords']:
if query.startswith(keyword + ' '):
return doc, DOCUMENTS[doc]['search_type']
error = {
"ERROR": "doc_type could not be determined from query",
"MESSAGE": 'Query supplied = ' + query
}
print_error(error)
return False, False


Expand Down
22 changes: 16 additions & 6 deletions healthtools/views/search_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from flask import Blueprint, request, jsonify

from healthtools.search import run_query
from healthtools.core import print_error

blueprint = Blueprint('search_api', __name__)

Expand All @@ -9,17 +10,26 @@
def index(doc_type=None):
query = request.args.get('q')

result, doc_type = run_query(query, doc_type)
try:
result, doc_type = run_query(query, doc_type)
response = jsonify({
'result': result,
'doc_type': doc_type,
'status': 'OK'
})

# Error with run_query (run_query returns false)
if not result:
return jsonify({
except Exception as err:
response = jsonify({
'result': {'hits': [], 'total': 0},
'doc_type': doc_type,
'status': 'FAILED',
'msg': '' # TODO: Pass run_query message here.
})
error = {
"ERROR": "index()",
"MESSAGE": str(err)
}
print_error(error)

# TODO: Log event here (send to Google Analytics)

return jsonify({'result': result, 'doc_type': doc_type, 'status': 'OK'})
return response
File renamed without changes.