Search code examples
google-app-engineasynchronoustornado

How do I port asynchronous calls from app engine to tornado?


App-engine asynchronous example:

from google.appengine.api import urlfetch

rpc = urlfetch.create_rpc()
urlfetch.make_fetch_call(rpc, "http://www.google.com/")

try:
    result = rpc.get_result()
    if result.status_code == 200:
        text = result.content
        # ...
except urlfetch.DownloadError:
    raise
return text

How do I do this in tornado? I've tried (using swirl) with something like:

import swirl

http = tornado.httpclient.AsyncHTTPClient()
uri = 'http://www.google.com/'

try:
    response = yield lambda cb: http.fetch(uri, cb)
    if response.code == 200:
        text = result.content
        # ...
except tornado.httpclient.HTTPError:
    raise
return text

But I get a Syntax Error because I can't have a return and a yield in the same function...


Solution

  • It appears that swirl doesn't provide any facilities for returning values from coroutines. Other frameworks that use this pattern, like NDB, let you raise a special 'return exception', or yield a return value, but swirl doesn't appear to provide this option. You'll need to restructure your coroutines to not return a value, instead.