Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Is it possible to do range specific file access over HTTP in python?

like image 466
Leke Avatar asked Jan 27 '11 08:01

Leke


2 Answers

Yes, it is possible to do it via HTTP using urllib2.

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. While using the same solution, all you need is set the bytes to -128. (The HTTP manual describes that when you do -value, it is the value quantity at the end of the response)

like image 186
Senthil Kumaran Avatar answered Oct 12 '22 23:10

Senthil Kumaran


You could try to only request the last 128 bytes using the Range header field:

Range: bytes=-128
like image 29
Gumbo Avatar answered Oct 13 '22 00:10

Gumbo