tuna vargi
software developer @ hipo
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")
PEP 3156
Coroutine
Future
Task
Generators calling other generators, generator delegation.
to remove callbacks
sequential query
async query with callback
def get(self):
def on_result(result):
self.write(result)
make_the_query(callback=on_result)
def get(self)
result = make_the_query()
self.write(result)
async query with sub-generator
def get(self)
result = yield from make_the_query()
self.write(result)
@asyncio.coroutine
def print_page(url):
response = yield from aiohttp.request('GET', url)
body = yield from response.read_and_close(decode=True)
print(body)
loop.run_until_complete(asyncio.wait([print_page('http://example.com/foo'),
print_page('http://example.com/bar')]))
import asyncio
@asyncio.coroutine
def factorial(name, number):
f = 1
for i in range(2, number+1):
print("Task %s: Compute factorial(%s)..." % (name, i))
yield from asyncio.sleep(1)
f *= i
print("Task %s: factorial(%s) = %s" % (name, number, f))
loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(factorial("A", 2)),
asyncio.ensure_future(factorial("B", 3)),
asyncio.ensure_future(factorial("C", 4))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
semi compatible with tornado and twisted