使用urllib3下载文件的最佳方法是什么? [英] What's the best way to download file using urllib3

查看:1507
本文介绍了使用urllib3下载文件的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 HTTP 协议使用 urllib3 下载文件。
我已经设法使用以下代码:

I would like to download file over HTTP protocol using urllib3. I have managed to do this using following code:

 url = 'http://url_to_a_file'
 connection_pool = urllib3.PoolManager()
 resp = connection_pool.request('GET',url )
 f = open(filename, 'wb')
 f.write(resp.data)
 f.close()
 resp.release_conn()

但我在想什么是正确的方法。
例如,它对于大文件可以正常工作,如果没有做什么来使此代码更容易扩展和扩展。

But I was wondering what is the proper way of doing this. For example will it work well for big files and If no what to do to make this code more bug tolerant and scalable.

注意。对于我来说,使用 urllib3 库不是 urllib2 是很重要的,因为我希望我的代码是线程安全的。

Note. It is important to me to use urllib3 library not urllib2 for example, because I want my code to be thread safe.

推荐答案

您的代码段很接近。值得注意的两件事:

Your code snippet is close. Two things worth noting:


  1. 如果您使用 resp.data ,它将消耗整个响应并返回连接(手动不需要 resp.release_conn())。如果您在内存中保存数据时很酷,这很好。

  1. If you're using resp.data, it will consume the entire response and return the connection (you don't need to resp.release_conn() manually). This is fine if you're cool with holding the data in-memory.

您可以使用 resp.read(amt)将流式传输响应,但连接需要通过 resp.release_conn()返回。

You could use resp.read(amt) which will stream the response, but the connection will need to be returned via resp.release_conn().

这看起来像...

import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)

with open(path, 'wb') as out:
    while True:
        data = r.read(chunk_size)
        if not data:
            break
        out.write(data)

r.release_conn()

在这种情况下,文档可能有点缺乏。如果任何人有兴趣制作拉动请求来改进urllib3文档,那将是非常感激的。 :)

The documentation might be a bit lacking on this scenario. If anyone is interested in making a pull-request to improve the urllib3 documentation, that would be greatly appreciated. :)

这篇关于使用urllib3下载文件的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆