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