Created
April 10, 2016 15:44
-
-
Save adow/46effbfb40fe2d0f1edbe43aab56830e to your computer and use it in GitHub Desktop.
fetch2.py
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
# -*- coding: utf-8 -*- | |
import tornado.ioloop | |
from tornado.httpclient import AsyncHTTPClient | |
import functools | |
task_list = [] | |
def callback(gen,task,v): | |
#print gen | |
#print task | |
#print v | |
try: | |
next_task = gen.send(v) #发送值 | |
next_task.completion = functools.partial(callback,gen,next_task) #下一次回调 | |
except StopIteration: | |
print 'stop' | |
class Task(object): | |
def complete(self,response): | |
self.completion(response) | |
def __init__(self): | |
self.v = None | |
self.completion = lambda :None | |
class FetchTask(Task): | |
def __init__(self,url): | |
super(FetchTask,self).__init__() | |
AsyncHTTPClient().fetch(url,self._callback) | |
def _callback(self,response): | |
self.complete(response) | |
def sync(func): | |
def wrapper(*wargs,**kwargs): | |
gen = func(*wargs,**kwargs) | |
task = gen.next() | |
task.completion = functools.partial(callback,gen,task) #第一次回调 | |
return wrapper | |
@sync | |
def fetch(url): | |
response = yield FetchTask(url) | |
print 1 | |
print response | |
response2 = yield FetchTask(url) | |
print 2 | |
print response2 | |
response3 = yield FetchTask(url) | |
print 3 | |
print response3 | |
fetch('http://codingnext.com') | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment