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?
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)
You could try to only request the last 128 bytes using the Range header field:
Range: bytes=-128
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With