12

用python下载大文件时,我想不仅对连接过程设置时间限制,还对下载设置时间限制。

我正在尝试使用以下 python 代码:

import requests

r = requests.get('http://ipv4.download.thinkbroadband.com/1GB.zip', timeout = 0.5, prefetch = False)

print r.headers['content-length']

print len(r.raw.read())

这不起作用(下载没有时间限制),正如文档中正确指出的那样:https ://requests.readthedocs.org/en/latest/user/quickstart/#timeouts

如果可能的话,那就太好了:

r.raw.read(timeout = 10)

问题是,如何对下载设置时间限制?

4

3 回答 3

11

答案是:不要使用请求,因为它是阻塞的。使用非阻塞网络 I/O,例如 eventlet:

import eventlet
from eventlet.green import urllib2
from eventlet.timeout import Timeout

url5 = 'http://ipv4.download.thinkbroadband.com/5MB.zip'
url10 = 'http://ipv4.download.thinkbroadband.com/10MB.zip'

urls = [url5, url5, url10, url10, url10, url5, url5]

def fetch(url):
    response = bytearray()
    with Timeout(60, False):
        response = urllib2.urlopen(url).read()
    return url, len(response)

pool = eventlet.GreenPool()
for url, length in pool.imap(fetch, urls):
    if (not length):
        print "%s: timeout!" % (url)
    else:
        print "%s: %s" % (url, length)

产生预期的结果:

http://ipv4.download.thinkbroadband.com/5MB.zip: 5242880
http://ipv4.download.thinkbroadband.com/5MB.zip: 5242880
http://ipv4.download.thinkbroadband.com/10MB.zip: timeout!
http://ipv4.download.thinkbroadband.com/10MB.zip: timeout!
http://ipv4.download.thinkbroadband.com/10MB.zip: timeout!
http://ipv4.download.thinkbroadband.com/5MB.zip: 5242880
http://ipv4.download.thinkbroadband.com/5MB.zip: 5242880
于 2012-11-27T20:42:52.250 回答
2

使用 Requests 的prefetch=False参数时,您可以一次提取任意大小的响应块(而不是一次全部提取)。

您需要做的是告诉 Requests 不要预加载整个请求,并保留您自己的时间来记录到目前为止您已经阅读了多少,同时一次获取小块。您可以使用r.raw.read(CHUNK_SIZE). 总体而言,代码将如下所示:

import requests
import time

CHUNK_SIZE = 2**12  # Bytes
TIME_EXPIRE = time.time() + 5  # Seconds

r = requests.get('http://ipv4.download.thinkbroadband.com/1GB.zip', prefetch=False)

data = ''
buffer = r.raw.read(CHUNK_SIZE)
while buffer:
    data += buffer
    buffer = r.raw.read(CHUNK_SIZE)

    if TIME_EXPIRE < time.time():
        # Quit after 5 seconds.
        data += buffer
        break

r.raw.release_conn()

print "Read %s bytes out of %s expected." % (len(data), r.headers['content-length'])

请注意,这有时可能会比分配的 5 秒多一点,因为决赛r.raw.read(...)可能会滞后任意时间。但至少它不依赖于多线程或套接字超时。

于 2012-11-27T03:46:02.093 回答
-3

在一个线程中运行下载,如果未按时完成,您可以中止该线程。

import requests
import threading

URL='http://ipv4.download.thinkbroadband.com/1GB.zip'
TIMEOUT=0.5

def download(return_value):
    return_value.append(requests.get(URL))

return_value = []
download_thread = threading.Thread(target=download, args=(return_value,))
download_thread.start()
download_thread.join(TIMEOUT)

if download_thread.is_alive():
    print 'The download was not finished on time...'
else:
    print return_value[0].headers['content-length']
于 2012-11-26T21:14:08.527 回答