Skip to content

Instantly share code, notes, and snippets.

@cleg
Created December 24, 2012 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cleg/4370563 to your computer and use it in GitHub Desktop.
Save cleg/4370563 to your computer and use it in GitHub Desktop.
Async tornado HTTP caller
@tornado.gen.engine
def async_request(self, callback, server_url, method=u'GET', body=None, **kwargs):
"""
Make async request to server
:param callback: callback to pass results
:type callback: func
:param server_url: path to required API
:type server_url: unicode
:param method: HTTP method to use, default - GET
:type method: unicode
:param body: HTTP request body for POST request, default - None
:type body: str or NoneType
:return: None
:rtype: NoneType
"""
args = {}
if kwargs:
args.update(kwargs)
url = '%s?%s' % (server_url, urlencode(args))
request = tornado.httpclient.HTTPRequest(url, method, body=body)
http = tornado.httpclient.AsyncHTTPClient()
response = yield tornado.gen.Task(http.fetch, request)
if response.error:
logging.warning("Error response %s fetching %s", response.error, response.request.url)
callback(None)
return
data = tornado.escape.json_decode(response.body) if response else None
callback(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment