tornado-同步异步下载图片

时间:2023-03-08 15:39:39

同步下载,阻塞

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)