annotate python2.py @ 956:263e64586aee

Added new python2.py server. Currently as GET server. Rejects all but localhost access
author Nicholas Jillings <nicholas.jillings@eecs.qmul.ac.uk>
date Tue, 26 May 2015 15:00:40 +0100
parents
children b1aca403bb59
rev   line source
nicholas@956 1 import BaseHTTPServer
nicholas@956 2 from os import walk
nicholas@956 3 from os import path
nicholas@956 4 import urllib2
nicholas@956 5
nicholas@956 6 def send404(s):
nicholas@956 7 s.send_response(404)
nicholas@956 8 s.send_header("Content-type", "text/html")
nicholas@956 9 s.end_headers()
nicholas@956 10
nicholas@956 11 def processFile(s):
nicholas@956 12 s.path = s.path[1:len(s.path)]
nicholas@956 13 st = s.path.rsplit(',')
nicholas@956 14 lenSt = len(st)
nicholas@956 15 fmt = st[lenSt-1].rsplit('.')
nicholas@956 16 size = path.getsize(urllib2.unquote(s.path))
nicholas@956 17 fileDump = open(urllib2.unquote(s.path))
nicholas@956 18 s.send_response(200)
nicholas@956 19
nicholas@956 20 if (fmt[1] == 'html'):
nicholas@956 21 s.send_header("Content-type", 'text/html')
nicholas@956 22 elif (fmt[1] == 'css'):
nicholas@956 23 s.send_header("Content-type", 'text/css')
nicholas@956 24 elif (fmt[1] == 'js'):
nicholas@956 25 s.send_header("Content-type", 'application/javascript')
nicholas@956 26 else:
nicholas@956 27 s.send_header("Content-type", 'application/octet-stream')
nicholas@956 28 s.send_header("Content-Length", size)
nicholas@956 29 s.end_headers()
nicholas@956 30 s.wfile.write(fileDump.read())
nicholas@956 31 fileDump.close()
nicholas@956 32
nicholas@956 33
nicholas@956 34 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
nicholas@956 35 def do_HEAD(s):
nicholas@956 36 s.send_response(200)
nicholas@956 37 s.send_header("Content-type", "text/html")
nicholas@956 38 s.end_headers()
nicholas@956 39 def do_GET(request):
nicholas@956 40 if(request.client_address[0] == "127.0.0.1"):
nicholas@956 41 if (request.path == "/favicon.ico"):
nicholas@956 42 send404(request)
nicholas@956 43 else:
nicholas@956 44 if (request.path == '/'):
nicholas@956 45 request.path = '/index.html'
nicholas@956 46 processFile(request)
nicholas@956 47 else:
nicholas@956 48 send404(request)
nicholas@956 49
nicholas@956 50 def run(server_class=BaseHTTPServer.HTTPServer,
nicholas@956 51 handler_class=MyHandler):
nicholas@956 52 server_address = ('', 8000)
nicholas@956 53 httpd = server_class(server_address, handler_class)
nicholas@956 54 httpd.serve_forever()
nicholas@956 55
nicholas@956 56 run()