File: base.py

package info (click to toggle)
python-sparkpost 1.3.10-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 512 kB
  • sloc: python: 2,528; makefile: 31; sh: 10
file content (33 lines) | stat: -rw-r--r-- 1,157 bytes parent folder | download | duplicates (4)
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
import json
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError

from .exceptions import SparkPostAPIException


class TornadoTransport(object):
    @gen.coroutine
    def request(self, method, uri, headers, **kwargs):
        if "data" in kwargs:
            kwargs["body"] = kwargs.pop("data")
        client = AsyncHTTPClient()
        try:
            response = yield client.fetch(uri, method=method, headers=headers,
                                          **kwargs)
        except HTTPError as ex:
            raise SparkPostAPIException(ex.response)
        if response.code == 204:
            raise gen.Return(True)
        if response.code == 200:
            result = None
            # noinspection PyBroadException
            try:
                result = json.loads(response.body.decode("utf-8"))
            # TODO: select exception to catch here
            except:  # noqa: E722
                pass
            if result:
                if 'results' in result:
                    raise gen.Return(result['results'])
                raise gen.Return(result)
        raise SparkPostAPIException(response)