Created
September 19, 2016 15:02
-
-
Save kitak/c7a7027fe46668f45f540f8c30ad0639 to your computer and use it in GitHub Desktop.
Flaskでpartial contentを実現
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mimetypes | |
import os | |
import re | |
from flask import Flask, request, send_file, Response | |
app = Flask(__name__, static_folder=".", static_url_path='') | |
@app.after_request | |
def after_request(response): | |
response.headers.add('Accept-Ranges', 'bytes') | |
return response | |
@app.route('/episode.mp3') | |
def send_file_partial(): | |
path = './episode.mp3' | |
range_header = request.headers.get('Range', None) | |
if not range_header: | |
return send_file(path) | |
size = os.path.getsize(path) | |
byte1, byte2 = 0, None | |
m = re.search('(\d+)-(\d*)', range_header) | |
g = m.groups() | |
if g[0]: | |
byte1 = int(g[0]) | |
if g[1]: | |
byte2 = int(g[1]) | |
length = size - byte1 | |
if byte2 != None: | |
length = byte2 - byte1 | |
data = None | |
with open(path, 'rb') as f: | |
f.seek(byte1) | |
data = f.read(length) | |
res = Response(data, | |
206, | |
mimetype=mimetypes.guess_type(path)[0], | |
direct_passthrough=True) | |
res.headers.add('Content-Range', 'bytes {0}-{1}/{2}'.format(byte1, byte1 + length - 1, size)) | |
return res | |
app.run(port=8080, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment