Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cant serve mp4 to browser

Im trying to serve a video file from my home WAMP server (windows 8) to the browser, but the browser keeps giving an error 500, and the apache logs says malformed header from script 's.py': Bad header: G@

"s.py" is my python version 3.4 script

n="\\wamp\\www\\r.mp4"
print ("Last-Modified: Fri, 24 Apr 2015 22:09:52 GMT")
print ("Accept-Ranges: bytes")
print ("Content-Length:", os.path.getsize(n))
print ("Content-type: video/mp4\r\n\r\n")

f=open(n, 'rb')
d=f.read()
sys.stdout.buffer.write(d)
sys.stdout.flush()
f.close()

i can run other simple python scripts on the server using the browser, so i know thats working, but for some reason it wont serve this mp4 file.

in the browser i call it using the URL "localhost/s.py", then it just gives error 500, and server log shows malformed header.

I been working on it all day, anybody have any idea how to solve it,

Thanks

like image 573
Paul Man Avatar asked Mar 20 '26 06:03

Paul Man


1 Answers

Python can be used to serve MP4 to you browser. But you can't throw a Python script to a WAMP server, like it was a PHP script.

If you were set on having a Python web application serve video through your Apache server, you'd have to build a WSGI application and look into mod_wsgi to be able to serve Python apps with Apache. You can also run the WSGI application without Apache.

An oversimplified WSGI application to serve mp4 video from a directory could be:

import os
from flask import Flask, send_file, make_response


APP = Flask(__name__)
MEDIA_PATH = '/path/to/your/media/directory'


@APP.route('/<vid_name>')
def serve_video(vid_name):
    vid_path = os.path.join(MEDIA_PATH, vid_name)
    resp = make_response(send_file(vid_path, 'video/mp4'))
    resp.headers['Content-Disposition'] = 'inline'
    return resp


if __name__ == '__main__':
    APP.run()
  1. Edit MEDIA_PATH with the full path to your the directory holding your videos.

  2. Save this script somewhere as video_server.py (for example).

  3. Run this script python video_server.py

  4. Via your browser, access to localhost:5000/some_video.mp4 (where some_vdeo.mp4 is the name of an existing video)

Note: You can edit APP.run() with the keyword arguments port and/or host:

  • port: to be able to listen on a different port. APP.run(port=8000)
  • host: to listen to requests from outside your computer. APP.run(host='0.0.0.0)

Edit: flask is an external library that needs to be installed. Look on the website for installation instructions. Simple version: pip install flask

like image 51
Luis Alvarez Avatar answered Mar 22 '26 20:03

Luis Alvarez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!