简体   繁体   English

通过http连接仅获取mp3文件的最后128个字节

[英]Fetch only the last 128 bytes of an mp3 file over a http connection

I have been looking for an example of how python could fetch only the last 128 bytes of an mp3 file over a http connection. 我一直在寻找python如何通过http连接仅获取mp3文件的最后128个字节的示例。 Is it possible to do range specific file access over HTTP in python? 是否可以在python中通过HTTP进行范围特定的文件访问?

Yes, it is possible to do it via HTTP using urllib2. 是的,可以使用urllib2通过HTTP完成。

class HTTPRangeHandler(urllib2.BaseHandler):

    def http_error_206(self, req, fp, code, msg, hdrs):
        # Range header supported
        r = urllib.addinfourl(fp, hdrs, req.get_full_url())
        r.code = code
        r.msg = msg
        return r

    def http_error_416(self, req, fp, code, msg, hdrs):
        # Range header not supported
        raise URLError('Requested Range Not Satisfiable')

opener = urllib2.build_opener(HTTPRangeHandler)
urllib2.install_opener(opener)

rangeheader = {'Range':'bytes=-128'}
req = urllib2.Request('http://path/to/your/file.mp3',headers=rangeheader)
res = urllib2.urlopen(req)
res.read()

The following SO question ( Python Seek on remote file ) had this asked/answered. 以下SO问题( 远程文件上的Python搜索 )有这个问/答。 While using the same solution, all you need is set the bytes to -128. 使用相同的解决方案时,您只需将字节设置为-128。 (The HTTP manual describes that when you do -value, it is the value quantity at the end of the response) (HTTP手册描述了当你做值时,它是响应结束时的值数量)

您可以尝试仅使用Range标头字段请求最后128个字节:

Range: bytes=-128

尝试使用httpheader模块(请参阅“使用http范围请求”示例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM