Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask import Flask, request, Response
- import os
- import re
- app = Flask(__name__)
- @app.route('/download/<filename>')
- def dmain_download(filename):
- return download_file(filename)
- def download_file(filename):
- file_path = os.path.join('/tmp', filename) # Update this, if the directory is different
- test_header = request.headers.get('Test-Header')
- if not os.path.exists(file_path):
- return "File not found", 404
- file_size = os.path.getsize(file_path)
- print("------------------------------------------------------------------------")
- range_header = request.headers.get('Range')
- print(f"Slice Range Header: {range_header}")
- print("------------------------------------------------------------------------")
- if not range_header:
- return send_full_file(file_path, filename, file_size)
- try:
- byte1, byte2 = 0, None
- m = re.search(r'bytes=(\d+)-(\d*)', range_header)
- if m:
- g = m.groups()
- byte1 = int(g[0])
- if g[1]:
- byte2 = int(g[1])
- # Adjust ranges if they are invalid
- if byte1 >= file_size:
- # If the start byte is greater than or equal to the file size,
- # it's an invalid range request per HTTP RFC.
- return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
- byte2 = min(byte2 if byte2 else file_size - 1, file_size - 1) # Clamp byte2 to file size
- length = byte2 - byte1 + 1
- with open(file_path, 'rb') as f:
- f.seek(byte1)
- data = f.read(length)
- rv = Response(data, 206, mimetype='application/octet-stream', direct_passthrough=True)
- rv.headers['Content-Range'] = f'bytes {byte1}-{byte2}/{file_size}'
- rv.headers['Accept-Ranges'] = 'bytes'
- rv.headers['Content-Length'] = str(length)
- rv.headers['Content-Disposition'] = f'attachment; filename={filename}'
- return rv
- except Exception as e:
- print(f"Error handling range request: {e}")
- return "Internal Server Error", 500
- def send_full_file(file_path, filename, file_size):
- with open(file_path, 'rb') as f:
- data = f.read()
- rv = Response(data, 200, mimetype='application/octet-stream', direct_passthrough=True)
- rv.headers['Accept-Ranges'] = 'bytes'
- rv.headers['Content-Length'] = str(file_size)
- rv.headers['Content-Disposition'] = f'attachment; filename={filename}'
- return rv
- if __name__ == '__main__':
- app.run(debug=True)
Advertisement
Add Comment
Please, Sign In to add comment