同步下载,阻塞
from tornado.httpclient import HTTPClient
url = 'http://fafafiajwoachwe.jpeg'
client = HTTPClient()
result = client.fetch(url)
img = result.body
with open('media/image', 'wb') as f:
f.write(img)
异步(协程coroutine+yield)下载,非阻塞
class GrabPicturesHandler(AuthBaseHandler):
@tornado.gen.coroutine # 1--------------
def post(self):
url = self.get_argument('url')
if not url:
return self.write('no url')
http_client = AsyncHTTPClient()
try:
response = yield http_client.fetch(url, request_timeout=6) #设置超时时间 # 2---------------
with open('media/image/xx.jpg', 'wb') as f:
f.write(response.body)
except AttributeError as e:
self.write(e)
转载于:https://www.cnblogs.com/tangpg/p/9518480.html
本文介绍使用Tornado框架进行图片的同步及异步下载方法。通过HTTPClient实现同步下载,使用AsyncHTTPClient配合coroutine和yield实现异步下载,避免阻塞。
3万+

被折叠的 条评论
为什么被折叠?



