Created
October 30, 2016 01:16
Answer of www.zhihu.com/question/51772677
This file contains hidden or 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 httpclient, gen, ioloop, concurrent | |
def fetch(urlList, minRequire): | |
resultList = [] | |
@gen.coroutine | |
def _fetch(): | |
fetchList = [httpclient.AsyncHTTPClient().fetch(url) for url in urlList] | |
yieldList = [concurrent.Future() for i in range(minRequire)] | |
def callback(f): | |
for yieldFuture in yieldList: | |
if not yieldFuture.done(): | |
print('Fetcheded: %s' % f.result().effective_url) | |
yieldFuture.set_result(f.result().body) | |
break | |
for fetchFuture in fetchList: | |
fetchFuture.add_done_callback(callback) | |
for yieldFuture in yieldList: | |
r = yield yieldFuture | |
resultList.append(r) | |
ioloop.IOLoop.current().run_sync(_fetch) | |
return resultList | |
if __name__ == '__main__': | |
urlList = ['http://127.0.0.1:5000/%s' % i for i in range(5)] | |
r = fetch(urlList, 3) | |
print(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment