# coding=utf-8# pylint:disable=invalid-name, len-as-condition"""Async http client"""import jsonimport loggingimport socketfrom tornado import genfrom tornado.httpclient import AsyncHTTPClient, HTTPErrorfrom tm.util.tm_exception import TMException_LOG = logging.getLogger(__name__)class AsyncHttpClient(object): """Async http client""" def __init__(self): param_dict = { "request_timeout": 10} self.__http_client = AsyncHTTPClient(None, defaults=param_dict) self.__protocol_prefix = "http://" self.__default_headers = { "Content-type": "application/json"} @gen.coroutine def post(self, url, headers=None, body=None): """Post""" resp = yield self.__fetch("POST", url, headers) raise gen.Return(resp) @gen.coroutine def get(self, url, headers=None): """Get""" resp = yield self.__fetch("GET", url, headers) raise gen.Return(resp) @gen.coroutine def delete(self, url, headers=None): """与get相同""" pass @gen.coroutine def put(self, url, headers=None, body=None): """与post相同""" pass @gen.coroutine def __fetch(self, url, request_type, headers=None, body=None): try: if body: body = json.dumps(body) url = self.__protocol_prefix + url resp = yield self.__http_client.fetch(url, method=request_type, headers=headers, body=body) return_value = (resp.code, json.loads(resp.body)) raise gen.Return(return_value) except HTTPError as http_error: err_msg = self.__log_error(http_error) raise gen.Return((http_error.code, err_msg)) except socket.error as e: _LOG.exception(e) raise gen.Return((503, str(e))) def __log_error(self, http_error): # pylint:disable=no-self-use err_msg = "Error info: %s \r\n" % str(http_error) if http_error.response: err_msg += "Body: %s \r\n" % str(http_error.response.body) _LOG.error(err_msg) if http_error.response: return json.loads(http_error.response.body) else: return str(http_error)def _check_resp(http_code, result): err_msg = "" if http_code != 201 and http_code != 200: err_msg += "Failed to connect to server.\r\n" else: if isinstance(result, dict): err_msg += result.get("error", "") else: err_msg += "Response body type is not dict.(%s)\r\n" % str(result) if err_msg: _LOG.error('Response: http_code: %d, result: %s', http_code, result) raise TMException(err_msg)
posted on 2018-09-04 08:09 阅读( ...) 评论( ...)