Passed
Push — master ( c8c370...dee89b )
by Osma
03:14
created

annif.backend.http.HTTPBackend._analyze()   B

Complexity

Conditions 6

Size

Total Lines 33
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 33
rs 8.2746
c 0
b 0
f 0
cc 6
nop 4
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