by lambda · 13y ago · 0 comments
@inlineCallbacks
def example():
try:
obtain_some_lock()
ui_status("Fetching file...")
result = yield fetch_file_from_server(args)
ui_status("Uploading file...")
yield post_file_to_other_server(result)
ui_status("Done.")
except SomeError as e:
ui_status("Error: %s" % e.msg)
finally:
release_some_lock()
I must say that this style of writing async code is much friendlier than descending into callback hell.There is work to make a similar async interface native in Python 3, in PEP 3156 http://www.python.org/dev/peps/pep-3156/, so this should become more widely available even to those who don't use Twisted.
class GenAsyncHandler(RequestHandler):
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.render("template.html")
(via http://www.tornadoweb.org/en/stable/gen.html ..)It handles all the plumbing for you with monkey-patching I/O calls. No annotations necessary, you just write linear code.
And the time machine spaketh: http://www.python.org/dev/peps/pep-3156/#coroutines-and-the-...
(it has no reason to "bubble up to the language spec", the language provides all the right primitives — especially with Python 3's `yield from`, it's up to the libraries to use them. That is a Good Thing.)