Created
December 30, 2013 06:01
-
-
Save mengzhuo/8178355 to your computer and use it in GitHub Desktop.
How Tornado gen.Task making Sync into Async function?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from tornado import gen, ioloop | |
import urllib2 | |
import re | |
tre = re.compile('\<title\>(?P<title>[^<]+)',re.IGNORECASE) | |
from pprint import pformat | |
@gen.coroutine | |
def sleep_bug(url): | |
print 'fetch:'+url | |
r = yield gen.Task(ioloop.IOLoop.current().add_callback) | |
print "callback "+ str(r) | |
title = tre.findall(urllib2.urlopen(url).read())[0].decode('utf-8') | |
print 'got from:'+url | |
raise gen.Return(title) | |
@gen.coroutine | |
def make_sleepy_bug(sec=3): | |
print "making..." | |
re = yield [sleep_bug('http://www.baidu.com'), | |
sleep_bug('http://www.google.com'), | |
sleep_bug('http://mengzhuo.org')] | |
raise gen.Return(re) | |
if __name__ == '__main__': | |
loop = ioloop.IOLoop.instance() | |
#print make_sleepy_bug() | |
print "done...\n"+pformat([unicode(x) for x in loop.run_sync(make_sleepy_bug)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment