From 72258ef46a1320c5dfbac986d2db809fa4e85545 Mon Sep 17 00:00:00 2001 From: richard-dds Date: Mon, 11 Jun 2018 14:49:52 -0400 Subject: [PATCH] Use tornado's AsyncHttpClient for ApiClient --- atst/api_client.py | 31 +++++++++++++++++++++---------- tests/test_api_client.py | 10 ++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) create mode 100644 tests/test_api_client.py diff --git a/atst/api_client.py b/atst/api_client.py index 5b787c7a..3a68f707 100644 --- a/atst/api_client.py +++ b/atst/api_client.py @@ -1,15 +1,13 @@ -import requests import tornado.gen -from concurrent.futures import ThreadPoolExecutor from tornado.httpclient import AsyncHTTPClient +from json import dumps, loads class ApiClient(object): def __init__(self, base_url): self.base_url = base_url - self.session = requests.Session() - self.executor = ThreadPoolExecutor() + self.client = AsyncHTTPClient() @tornado.gen.coroutine def get(self, path, **kwargs): @@ -17,19 +15,32 @@ class ApiClient(object): @tornado.gen.coroutine def put(self, path, **kwargs): - return self.make_request('PUT', self.base_url + path, **kwargs) + return (yield self.make_request('PUT', self.base_url + path, **kwargs)) @tornado.gen.coroutine def post(self, path, **kwargs): - return self.make_request('POST', self.base_url + path, **kwargs) + return (yield self.make_request('POST', self.base_url + path, **kwargs)) @tornado.gen.coroutine def delete(self, path, **kwargs): - return self.make_request('DELETE', self.base_url + path, **kwargs) + return (yield self.make_request('DELETE', self.base_url + path, **kwargs)) @tornado.gen.coroutine def make_request(self, method, url, **kwargs): - def _make_request(_method, _url, **kwargs): - return requests.request(_method, _url, **kwargs) + # If 'json' kwarg is specified, serialize it to 'body' and update + # the Content-Type. + if 'json' in kwargs: + kwargs['body'] = dumps(kwargs['json']) + del kwargs['json'] + headers = kwargs.get('headers', {}) + headers['Content-Type'] = 'application-json' + kwargs['headers'] = headers - return (yield self.executor.submit(_make_request, 'GET', url)) + response = yield self.client.fetch(url, method=method, **kwargs) + return self.adapt_response(response) + + def adapt_response(self, response): + if response.headers['Content-Type'] == 'application/json': + json = loads(response.body) + setattr(response, 'json', json) + return response diff --git a/tests/test_api_client.py b/tests/test_api_client.py new file mode 100644 index 00000000..9e18fad6 --- /dev/null +++ b/tests/test_api_client.py @@ -0,0 +1,10 @@ +import pytest + +from atst.api_client import ApiClient + + +@pytest.mark.gen_test +def test_api_client(http_client, base_url): + client = ApiClient(base_url) + response = yield client.get('') + assert response.code == 200