client.py 1.21 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import requests
import logging
from . import models

logger = logging.getLogger(__name__)


class Client(object):
    def __init__(self, endpoint):
        self.endpoint = endpoint

    def analyse(self, input, method='GET', **kwargs):
        return self.request('/', method=method, input=input, **kwargs)

    def request(self, path=None, method='GET', **params):
        url = '{}{}'.format(self.endpoint, path)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
17
        response = requests.request(method=method, url=url, params=params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
18 19 20 21 22 23 24 25 26 27 28 29
        try:
            resp = models.from_dict(response.json())
            resp.validate(resp)
            return resp
        except Exception as ex:
            logger.error(('There seems to be a problem with the response:\n'
                          '\tURL: {url}\n'
                          '\tError: {error}\n'
                          '\t\n'
                          '#### Response:\n'
                          '\tCode: {code}'
                          '\tContent: {content}'
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30 31 32 33 34
                          '\n').format(
                              error=ex,
                              url=url,
                              code=response.status_code,
                              content=response.content))
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35
            raise ex