Guest User

Untitled

a guest
Jul 14th, 2014
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import os
  4. import time
  5. import urllib.request
  6. import http.server
  7. import numpy
  8. from PIL import Image
  9.  
  10. if not os.path.exists('jquery.min.js'):
  11.     response = urllib.request.urlopen("http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js")
  12.     open('jquery.min.js','wb').write(response.read())
  13.     print('need download')
  14.  
  15. class MyHandler(http.server.BaseHTTPRequestHandler):
  16.     def do_HEAD(s):
  17.         s.send_response(200)
  18.         s.send_header("Content-type", "text/html")
  19.         s.end_headers()
  20.  
  21.     def getIndex(s):
  22.         s.send_response(200)
  23.         s.send_header("Content-type", "text/html")
  24.         s.end_headers()
  25.         s.wfile.write(b'''<html><head><title>Title goes here.</title></head>
  26. <body style="margin:0; padding:0">
  27. <div id = "video" style = "width:100%; height:100%">
  28.   <img style = "width:100%; height:100%"/>
  29. </div>
  30. <script src="jquery.min.js"></script>
  31. <script type="text/javascript">
  32.   setInterval(function(){
  33.       $('#video > img').attr('src', 'jpg?random=' + Math.random())
  34.   }, 300);
  35. </script>
  36. </body></html>
  37. ''')
  38.     def getJQuery(s):
  39.         s.send_response(200)
  40.         s.send_header("Content-type", "application/x-javascript")
  41.         s.end_headers()
  42.         s.wfile.write(open('jquery.min.js','rb').read())
  43.  
  44.     def getJpg(s):
  45.         s.send_response(200)
  46.         s.end_headers()
  47.         a = numpy.random.rand(720,1280,3) * 255
  48.         image = Image.fromarray(a.astype('uint8')).convert('RGBA')
  49.         image.save(s.wfile, "JPEG")
  50.  
  51.     getDict = {
  52.         '/': getIndex,
  53.         '/jquery.min.js': getJQuery,
  54.     }
  55.  
  56.     def do_GET(s):
  57.         path = str(s.path)
  58.         if path in s.getDict:
  59.             s.getDict[path](s)
  60.         elif '/jpg?random=' in path:
  61.             s.getJpg()
  62.         else:
  63.             print('s.path: >>'+path+'<<')
  64.  
  65. HOST_NAME = '127.0.0.1'
  66. PORT_NUMBER = 8000
  67.  
  68. if __name__ == '__main__':
  69.     server_class = http.server.HTTPServer
  70.     httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
  71.     print(time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER))
  72.     try:
  73.         httpd.serve_forever()
  74.     except KeyboardInterrupt:
  75.         pass
  76.     httpd.server_close()
  77.     print(time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))
Advertisement
Add Comment
Please, Sign In to add comment