5

我想以多线程模式下载文件,这里有以下代码:

#!/usr/bin/env python

import httplib


def main():
    url_opt = '/film/0d46e21795209bc18e9530133226cfc3/7f_Naruto.Uragannie.Hroniki.001.seriya.a1.20.06.13.mp4'

    headers = {}
    headers['Accept-Language'] = 'en-GB,en-US,en'
    headers['Accept-Encoding'] = 'gzip,deflate,sdch'
    headers['Accept-Charset'] = 'max-age=0'
    headers['Cache-Control'] = 'ISO-8859-1,utf-8,*'
    headers['Cache-Control'] = 'max-age=0'
    headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 5.1)'
    headers['Connection'] = 'keep-alive'
    headers['Accept'] = 'text/html,application/xhtml+xml,application/xml,*/*'
    headers['Range'] = ''

    conn = httplib.HTTPConnection('data09-cdn.datalock.ru:80')
    conn.request("GET", url_opt, '', headers)

    print "Request sent"

    resp = conn.getresponse()
    print resp.status
    print resp.reason
    print resp.getheaders()

    file_for_wirte = open('cartoon.mp4', 'w')
    file_for_wirte.write(resp.read())

    print resp.read()

    conn.close()


if __name__ == "__main__":
    main()

这是输出:

Request sent
200
OK
[('content-length', '62515220'), ('accept-ranges', 'bytes'), ('server', 'nginx/1.2.7'), ('last-modified', 'Thu, 20 Jun 2013 12:10:43 GMT'), ('connection', 'keep-alive'), ('date', 'Fri, 14 Feb 2014 07:53:30 GMT'), ('content-type', 'video/mp4')]

这段代码运行良好,但是我不明白如何通过文档下载使用范围的文件。如果您看到响应的输出,则表明哪个服务器提供:

 ('content-length', '62515220'), ('accept-ranges', 'bytes')

它支持以“字节”为单位的范围,其中内容大小为 62515220

但是在此请求中下载了整个文件。但是我想首先获取服务器信息,比如这个文件是否可以使用http范围查询和文件的内容大小来支持而无需下载?以及如何创建具有范围的 http 查询(即:0~25000)?

4

1 回答 1

14

Range将标头bytes=start_offset-end_offset作为范围说明符传递。

例如,以下代码检索前 300 个字节。( 0-299):

>>> import httplib
>>> conn = httplib.HTTPConnection('localhost')
>>> conn.request("GET", '/', headers={'Range': 'bytes=0-299'}) # <----
>>> resp = conn.getresponse()
>>> resp.status
206
>>> resp.status == httplib.PARTIAL_CONTENT
True
>>> resp.getheader('content-range')
'bytes 0-299/612'
>>> content = resp.read()
>>> len(content)
300

NOTE Both start_offset, end_offset are inclusive.

UPDATE

If the server does not understand Range header, it will respond with the status code 200 (httplib.OK) instead of 206 (httplib.PARTIAL_CONTENT), and it will send whole content. To make sure the server respond partial content, check the status code.

>>> resp.status == httplib.PARTIAL_CONTENT
True
于 2014-02-14T10:07:06.960 回答