| 1 |
import json |
| 2 |
from tornado import gen |
| 3 |
from tornado.httpclient import AsyncHTTPClient, HTTPError |
| 4 |
|
| 5 |
from .exceptions import SparkPostAPIException |
| 6 |
|
| 7 |
|
| 8 |
class TornadoTransport(object): |
| 9 |
@gen.coroutine |
| 10 |
def request(self, method, uri, headers, **kwargs): |
| 11 |
if "data" in kwargs: |
| 12 |
kwargs["body"] = kwargs.pop("data") |
| 13 |
client = AsyncHTTPClient() |
| 14 |
try: |
| 15 |
response = yield client.fetch(uri, method=method, headers=headers, |
| 16 |
**kwargs) |
| 17 |
except HTTPError as ex: |
| 18 |
raise SparkPostAPIException(ex.response) |
| 19 |
if response.code == 204: |
| 20 |
raise gen.Return(True) |
| 21 |
if response.code == 200: |
| 22 |
result = None |
| 23 |
# noinspection PyBroadException |
| 24 |
try: |
| 25 |
result = json.loads(response.body.decode("utf-8")) |
| 26 |
# TODO: select exception to catch here |
| 27 |
except: # noqa: E722 |
| 28 |
pass |
| 29 |
if result: |
| 30 |
if 'results' in result: |
| 31 |
raise gen.Return(result['results']) |
| 32 |
raise gen.Return(result) |
| 33 |
raise SparkPostAPIException(response) |