Sigma65535
Sigma65535

Reputation: 381

how to use tornado to get image and write it in a file?

I have a url :"https://findicons.com/files/icons/2787/beautiful_flat_icons/128/running.png"

I want to get the image and write it to file , i write the code as follow:

import urllib.request
web = urllib.request.urlopen(iturl)
itdata = web.read()
f = open(str(cou) + '.png', "wb")
cou = cou + 1
f.write(itdata)
f.close()

My question is ,if i have many urls to download ,how can i implement it by coroutine of tornado?

Upvotes: 0

Views: 756

Answers (1)

notorious.no
notorious.no

Reputation: 5107

This isn't the entire code, just something I came up with in 5 mins but it should give you enough information to satisfy your requirements. If you have any questions or further explanation is required, please let me know.

from tornado import gen, httpclient, ioloop

@gen.coroutine
def main():
    client = httpclient.AsyncHTTPClient()
    response = yield client.fetch(
        'https://findicons.com/files/icons/2787/beautiful_flat_icons/128/running.png',
        download_image,
        follow_redirects = True)

@gen.coroutine
def download_image(response):
    buffer_size = 1024
    filename = response.request.url.split('/')[-1]  # this is not always reliable
    with open(filename, 'ab') as img:
        while True:
            chunk = response.buffer.read(buffer_size)
            if chunk == '':
                break
            img.write(chunk)
            yield

ioloop.IOLoop.current().run_sync(main)

References

Upvotes: 1

Related Questions