潭州课堂25班:Ph201805201 tornado 项目 第十课 深入应用异步和协程(课堂笔记)
tornado 相关说明
需求: 增加 /save 的 handler,实现异步保存指定 URL 图片的功能
从网页上得到一张图片地址,由这个地址将图片保存到服务器,并将相关数据保存到数据库
import requests
from .main import AuthBaseHandler
from utlis.photo import UploadImg, add_post_for
class SyncSaveHandler(AuthBaseHandler): """同步版本的保存 url """ def get(self, *args, **kwargs): save_url = self.get_argument('save_url', None) res = requests.get(save_url) uim = UploadImg('a.jpg', self.settings['static_path']) uim.save_upload(res.content) uim.save_thumb() post = add_post_for(self.current_user, uim.upload_url, uim.thumb_url) # post = add_post_for(username, uim.upload_url, uim.thumb_url) self.redirect('/post/{}'.format(post.id))
from tornado.gen import coroutine # 装饰器
from tornado.httpclient import AsyncHTTPClient # 异步模块
from .main import AuthBaseHandler
from utlis.photo import UploadImg, add_post_for
class AyncSaveHandler(AuthBaseHandler): """异步版本保存 URL""" @coroutine def get(self, *args, **kwargs): save_url = self.get_argument('save_url', None) username = self.get_argument('name', None) client = AsyncHTTPClient() # res = requests.get(save_url) res = yield client.fetch(save_url, request_timeout=20) uim = UploadImg('a.jpg', self.settings['static_path']) uim.save_upload(res.body) uim.save_thumb() post = add_post_for(self.current_user, uim.upload_url, uim.thumb_url) # post = add_post_for(username, uim.upload_url, uim.thumb_url) self.redirect('/post/{}'.format(post.id))