handler_transmart.py 2.2 KB
Newer Older
1
2
3
"""This module provides TransmartHandler, an implementation of ETLHandler for
tranSMART."""

Sascha Herzinger's avatar
Sascha Herzinger committed
4
5
import logging

6
7
8
9
10
import requests

from fractalis.data.etlhandler import ETLHandler


Sascha Herzinger's avatar
Sascha Herzinger committed
11
12
13
logger = logging.getLogger(__name__)


14
15
16
17
class TransmartHandler(ETLHandler):
    """This ETLHandler provides integration with tranSMART.

    'tranSMART is a knowledge management platform that enables scientists to
18
19
20
    develop and refine research hypotheses by investigating correlations
    between genetic and phenotypic data, and assessing their analytical results
    in the context of published literature and other work.'
21
22
23
24
25
26
27
28

    Project URL: https://github.com/transmart
    """

    _handler = 'transmart'

    @staticmethod
    def make_label(descriptor: dict) -> str:
29
        return descriptor['label']
30

Sascha Herzinger's avatar
Sascha Herzinger committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    def _get_token_for_credentials(self, server: str, auth: dict) -> str:
        try:
            user = auth['user']
            passwd = auth['passwd']
            if len(user) == 0 or len(passwd) == 0:
                raise KeyError
        except KeyError:
            error = "The authentication object must contain the non-empty " \
                    "fields 'user' and 'passwd'."
            logger.error(error)
            raise ValueError(error)
        r = requests.post(url=server + '/oauth/token',
                          params={
                              'grant_type': 'password',
                              'client_id': 'glowingbear-js',
                              'client_secret': '',
                              'username': user,
                              'password': passwd
                          },
50
51
                          headers={'Accept': 'application/json'},
                          timeout=10)
52
        if r.status_code != 200:
53
54
55
56
            error = "Could not authenticate. " \
                    "Reason: [{}]: {}".format(r.status_code, r.text)
            logger.error(error)
            raise ValueError(error)
Sascha Herzinger's avatar
Sascha Herzinger committed
57
58
59
        try:
            response = r.json()
            return response['access_token']
60
61
62
63
64
        except Exception:
            error = "Could not authenticate. " \
                    "Got unexpected response: '{}'".format(r.text)
            logger.error(error)
            raise ValueError(error)