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?
Asked
Active
Viewed 1,222 times
3 Answers
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
-
You should include, that the code should check if the returned HTTP-Status is 206 (Partial Content) instead of 200 (OK). This way it should be possible to detect wether the server supported the Rang-Header. – Martin Thurau Jan 27 '11 at 09:44
-
@Martin. Yes, it should be. Updated. – Senthil Kumaran Jan 27 '11 at 11:04
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