def PatchPage(url, body): client = AsyncHTTPClient.configurable_default()() request = TornadoDataRequest(url, method="PATCH", body=body) try: response = yield client.fetch(request) except HTTPError, e: response = e
class MockAsyncHTTPClient(AsyncHTTPClient.configurable_default()): mocks = {} records = {} def url_key(self, url): """cache key is url without query to avoid caching things like access tokens """ return url.split('?')[0] def fetch_mock(self, request): """Fetch a mocked request Arguments: request (HTTPRequest): the request to fetch Returns: HTTPResponse constructed from the info stored in the mocks Raises: HTTPError if the cached response has status >= 400 """ mock_data = self.mocks[self.url_key(request.url)] code = mock_data.get('code', 200) headers = HTTPHeaders(mock_data.get('headers', {})) response = HTTPResponse(request, code, headers=headers) response.buffer = io.BytesIO(mock_data['body'].encode('utf8')) if code >= 400: raise HTTPError(mock_data['code'], response=response) return response def _record_response(self, url_key, response): """Record a response in self.records""" self.records[url_key] = { 'code': response.code, 'headers': dict(response.headers), 'body': response.body.decode('utf8'), } async def fetch(self, req_or_url, *args, **kwargs): """Mocked HTTP fetch If the request URL is in self.mocks, build a response from the cached response. Otherwise, run the actual request and store the response in self.records. """ if isinstance(req_or_url, HTTPRequest): request = req_or_url else: request = HTTPRequest(req_or_url, *args, **kwargs) url_key = self.url_key(request.url) if url_key in self.mocks: fetch = self.fetch_mock else: fetch = super().fetch error = None try: response = await gen.maybe_future(fetch(request)) except HTTPError as e: error = e response = e.response self._record_response(url_key, response) # return or raise the original result if error: raise error else: return response
#coding=utf-8 import logging import json import traceback from urllib import urlencode from tornado.httputil import url_concat from tornado.httpclient import AsyncHTTPClient from tornado.gen import coroutine, Return LOG = logging.getLogger() AsyncHTTPClient.configure(AsyncHTTPClient.configurable_default(), **{'max_clients': 65535}) class BaseApi(object): HEADERS = { 'Accept-Language': 'zh-cn', 'User-Agent': 'Tudou API', "Accept-Charset": "utf-8" } @classmethod @coroutine def get(cls, path, params='', host='', header=None, conn_timeout=None, req_timeout=None):