I'm trying to get data from an url as a file and serve it back with the right mimetype. I've tried a lot of different options this is some of the python flask code I currently have
## download video
@app.route('/download/<string:resource>')
def download(resource):
asset = getasset(resource)
# headers = {"Content-Type":"application/octet-stream","Accept-Encoding":"gzip, deflate, br","Accept":"*/*"}
response = requests.get(asset['downloads']['h264_720'], stream=True)
# length = response.headers.get('Content-Length')
def exhaust(response):
while True:
response.raw.decode_content = True
out = response.content.read(1024*1024)
if not out:
break
yield out
if IS_OFFLINE:
return Response(exhaust(response), mimetype='video/mp4')
else:
return Response(base64.b64decode(exhaust(response)), mimetype='video/mp4')
Offline the response is fine reviewing it locally with "serverless wsgi serve --stage dev"
Online the response is different (after doing "serverless deploy --stage dev"...
Please have a look at the image, left the correct mp4 video file. Right a file that is bigger and not a mp4 file.
It has something to do with base64.b64encode(r.content) but there is more to it. I started of with this function:
### download video
# @app.route('/download/<string:resource>')
# def download(resource):
# asset = getasset(resource)
# r = requests.get(asset['downloads']['h264_720'],stream=True)
# if IS_OFFLINE:
# return Response(r.content, mimetype='video/mp4')
# else:
# return Response(base64.b64decode(r.content), mimetype='video/mp4')
This results in a file that looks like this and is only 200 bytes:
ftypisomisomiso2avc1mp41moovlmvhdTtraktkhd8edtselst8treftmcdmdiamdhd2UhdlrvideVideoHandlerjminfvmhddinfdrefurlstblstsdavc1HH9avcCMgMPfxrhcolrnclxpaspbtrtq+Vsttsstss3estscstszOBNC7468x69G8BClAiBBKGHAEArLiDGuc=
It has some of the first characters that I can see in the correct file:
Any one knows what's going on and how to fix it?
I did manage to reproduce the issue locally:
import requests
import base64
url = 'to a video file...'
r = requests.get(url)
with open("test.mp4", "wb") as out_file:
#reproducing the issue with this
base64_bytes = base64.b64encode(r.content)
#uncomment this will produce correct output
#message_bytes = base64.b64decode(base64_bytes)
out_file.write(message_bytes)

