项目 09 深入应用异步和协程
handlers/service.py 创建一个新的py文件
import time from datetime import datetime import tornado.httpclient import tornado.gen import tornado.web from .main import AuthBaseHandler from utils import photo, account
class SyncImageHandler(AuthBaseHandler): ''' 原始版本,非异步 ''' @tornado.web.authenticated def get(self): resp = self.fetch_image() if not resp.body: self.write('empty data') return img_saver = photo.ImageSave(self.settings['static_path'], 'x.jpg') img_saver.save_upload(resp.body) # body 就是图片数据 img_saver.make_thumb() # 做缩略图 post = account.add_post_for(self.current_user, img_saver.upload_url, img_saver.thumb_url) # 添加到数据库,拿到 post 实例 self.redirect('/post/{}'.format(post.id)) # 跳转到 post 页面 def fetch_image(self): """ 用内部客户端去下载图片 """ url = self.get_argument("url", None) # 取 ?url= 的值 client = tornado.httpclient.HTTPClient() print("---going to fetch:{}".format(url)) resp = client.fetch(url) return resp
import time from datetime import datetime import tornado.httpclient import tornado.gen import tornado.web from .main import AuthBaseHandler from utils import photo, account class ImageHandler(AuthBaseHandler): """ 异步版本 """ @tornado.web.authenticated @tornado.gen.coroutine def get(self): resp = yield self.fetch_image() #在会发生阻塞的地方加上yield,并在函数上面加上装饰器@tornado.gen.coroutine if not resp.body: self.write('empty data') return img_saver = photo.ImageSave(self.settings['static_path'], 'x.jpg') img_saver.save_upload(resp.body) # body 就是图片数据 img_saver.make_thumb() # 做缩略图 post = account.add_post_for(self.current_user, img_saver.upload_url, img_saver.thumb_url) # 添加到数据库,拿到 post 实例 print("-- {} -end fetch:#{}".format(datetime.now(), post.id)) self.redirect('/post/{}'.format(post.id)) # 跳转到 post 页面 # @tornado.gen.coroutine def fetch_image(self): """ 用内部客户端去下载图片 """ url = self.get_argument("url", None) # 取 ?url= 的值 client = tornado.httpclient.AsyncHTTPClient() #异步的版本需要在这里改变获取用户的方式 print("-- {} -going to fetch:{}".format(datetime.now(), url)) # yield tornado.gen.sleep(6) # resp = client.fetch(url) return client.fetch(url)
并在app.py里面添加路由