/
http.py
46 lines (37 loc) · 1.65 KB
/
http.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""HTTP/REST client backend that makes calls to a web service
and returns the results"""
import requests
import requests.exceptions
from annif.suggestion import SubjectSuggestion, ListSuggestionResult
from . import backend
class HTTPBackend(backend.AnnifBackend):
name = "http"
def _suggest(self, text, params):
data = {'text': text}
if 'project' in params:
data['project'] = params['project']
try:
req = requests.post(params['endpoint'], data=data)
req.raise_for_status()
except requests.exceptions.RequestException as err:
self.warning("HTTP request failed: {}".format(err))
return ListSuggestionResult([], self.project.subjects)
try:
response = req.json()
except ValueError as err:
self.warning("JSON decode failed: {}".format(err))
return ListSuggestionResult([], self.project.subjects)
if 'results' in response:
results = response['results']
else:
results = response
try:
return ListSuggestionResult([SubjectSuggestion(uri=h['uri'],
label=h['label'],
score=h['score'])
for h in results
if h['score'] > 0.0],
self.project.subjects)
except (TypeError, ValueError) as err:
self.warning("Problem interpreting JSON data: {}".format(err))
return ListSuggestionResult([], self.project.subjects)