5

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?

Leke
  • 873
  • 3
  • 15
  • 28

3 Answers3

9

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)

Community
  • 1
  • 1
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
5

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

Range: bytes=-128
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

Try the httpheader module (see the "Using http range requests" example).

initall
  • 2,385
  • 19
  • 27