具有多个连接的请求

2024-04-26 09:46:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python请求库下载一个大文件,例如:

r = requests.get("http://bigfile.com/bigfile.bin")
content = r.content

大文件下载速度为每秒+30kb,这有点慢。到bigfile服务器的每个连接都被限制,因此我希望建立多个连接。

有没有办法同时建立多个连接来下载一个文件?


Tags: 文件服务器comhttpgetbincontentrequests
3条回答

下面是一个Python脚本,它将给定的url保存到一个文件,并使用多个线程下载它:

#!/usr/bin/env python
import sys
from functools import partial
from itertools import count, izip
from multiprocessing.dummy import Pool # use threads
from urllib2 import HTTPError, Request, urlopen

def download_chunk(url, byterange):
    req = Request(url, headers=dict(Range='bytes=%d-%d' % byterange))
    try:
        return urlopen(req).read()
    except HTTPError as e:
        return b''  if e.code == 416 else None  # treat range error as EOF
    except EnvironmentError:
        return None

def main():
    url, filename = sys.argv[1:]
    pool = Pool(4) # define number of concurrent connections
    chunksize = 1 << 16
    ranges = izip(count(0, chunksize), count(chunksize - 1, chunksize))
    with open(filename, 'wb') as file:
        for s in pool.imap(partial(download_part, url), ranges):
            if not s:
                break # error or EOF
            file.write(s)
            if len(s) != chunksize:
                break  # EOF (servers with no Range support end up here)

if __name__ == "__main__":
    main()

如果服务器返回空正文或416 http代码,或者如果响应大小不是chunksize,则检测到文件结尾。

它支持不理解Range头的服务器(在本例中,所有内容都在单个请求中下载;要支持大型文件,请更改download_chunk()以保存到临时文件,并返回要在主线程中读取的文件名,而不是文件内容本身)。

它允许独立地更改单个http请求中请求的并发连接数(池大小)和字节数。

要使用多个进程而不是线程,请更改导入:

from multiprocessing.pool import Pool # use processes (other code unchanged)

您可以使用HTTP^{}头来获取文件的一部分(already covered for python here)。

只需启动几个线程,每个线程获取不同的范围,就完成了;)

def download(url,start):
    req = urllib2.Request('http://www.python.org/')
    req.headers['Range'] = 'bytes=%s-%s' % (start, start+chunk_size)
    f = urllib2.urlopen(req)
    parts[start] = f.read()

threads = []
parts = {}

# Initialize threads
for i in range(0,10):
    t = threading.Thread(target=download, i*chunk_size)
    t.start()
    threads.append(t)

# Join threads back (order doesn't matter, you just want them all)
for i in threads:
    i.join()

# Sort parts and you're done
result = ''.join(parts[i] for i in sorted(parts.keys()))

还要注意,并非每个服务器都支持Range头(尤其是具有php scripts responsible for data fetching的服务器通常不实现对它的处理)。

这个解决方案需要名为“aria2c”的linux实用程序,但它的优点是很容易恢复下载。

它还假设要下载的所有文件都列在位置MY_HTTP_LOC的http目录列表中。我在lighttpd/1.4.26http服务器的一个实例上测试了这个脚本。但是,您可以很容易地修改此脚本,使其适用于其他设置。

#!/usr/bin/python

import os
import urllib
import re
import subprocess

MY_HTTP_LOC = "http://AAA.BBB.CCC.DDD/"

# retrieve webpage source code
f = urllib.urlopen(MY_HTTP_LOC)
page = f.read()
f.close

# extract relevant URL segments from source code
rgxp = '(\<td\ class="n"\>\<a\ href=")([0-9a-zA-Z\(\)\-\_\.]+)(")'
results =  re.findall(rgxp,str(page))
files = []
for match in results:
    files.append(match[1])

# download (using aria2c) files
for afile in files:
    if os.path.exists(afile) and not os.path.exists(afile+'.aria2'):
        print 'Skipping already-retrieved file: ' + afile
    else:
        print 'Downloading file: ' + afile          
        subprocess.Popen(["aria2c", "-x", "16", "-s", "20", MY_HTTP_LOC+str(afile)]).wait()

相关问题 更多 >