4

以下代码是一个非异步代码示例,有什么方法可以异步获取图像吗?

import urllib
for x in range(0,10):
        urllib.urlretrieve("http://test.com/file %s.png" % (x), "temp/file %s.png" % (x))

我也看过Grequests库,但如果可能的话,或者如何从文档中做到这一点,我想不出太多。

4

2 回答 2

12

您不需要任何第三方库。只需为每个请求创建一个线程,启动线程,然后等待所有线程在后台完成,或者在下载图像时继续您的应用程序。

import threading

results = []
def getter(url, dest):
   results.append(urllib.urlretreave(url, dest))

threads = []
for x in range(0,10):
    t = threading.Thread(target=getter, args=('http://test.com/file %s.png' % x,
                                              'temp/file %s.png' % x))
    t.start()
    threads.append(t)
# wait for all threads to finish
# You can continue doing whatever you want and
# join the threads when you finally need the results.
# They will fatch your urls in the background without
# blocking your main application.
map(lambda t: t.join(), threads)

或者,您可以创建一个将从队列获取urlsdests从队列获取的线程池。

如果您使用的是 Python 3,它已经在futures模块中为您实现。

于 2013-08-22T10:22:29.527 回答
3

像这样的东西应该可以帮助你

import grequests
urls = ['url1', 'url2', ....] # this should be the list of urls

    requests = (grequests.get(u) for u in urls)
    responses = grequests.map(requests)
    for response in responses:
        if 199 < response.status_code < 400:
             name = generate_file_name()    # generate some name for your image file with extension like example.jpg
             with open(name, 'wb') as f:    # or save to S3 or something like that
                  f.write(response.content)

这里只有图像的下载是并行的,但将每个图像内容写入文件将是顺序的,因此您可以创建一个线程或执行其他操作以使其并行或异步

于 2013-08-22T10:23:52.077 回答