comparison 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
comparison
equal deleted inserted replaced
955:4b29eddf74ea 956:263e64586aee
1 import BaseHTTPServer
2 from os import walk
3 from os import path
4 import urllib2
5
6 def send404(s):
7 s.send_response(404)
8 s.send_header("Content-type", "text/html")
9 s.end_headers()
10
11 def processFile(s):
12 s.path = s.path[1:len(s.path)]
13 st = s.path.rsplit(',')
14 lenSt = len(st)
15 fmt = st[lenSt-1].rsplit('.')
16 size = path.getsize(urllib2.unquote(s.path))
17 fileDump = open(urllib2.unquote(s.path))
18 s.send_response(200)
19
20 if (fmt[1] == 'html'):
21 s.send_header("Content-type", 'text/html')
22 elif (fmt[1] == 'css'):
23 s.send_header("Content-type", 'text/css')
24 elif (fmt[1] == 'js'):
25 s.send_header("Content-type", 'application/javascript')
26 else:
27 s.send_header("Content-type", 'application/octet-stream')
28 s.send_header("Content-Length", size)
29 s.end_headers()
30 s.wfile.write(fileDump.read())
31 fileDump.close()
32
33
34 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
35 def do_HEAD(s):
36 s.send_response(200)
37 s.send_header("Content-type", "text/html")
38 s.end_headers()
39 def do_GET(request):
40 if(request.client_address[0] == "127.0.0.1"):
41 if (request.path == "/favicon.ico"):
42 send404(request)
43 else:
44 if (request.path == '/'):
45 request.path = '/index.html'
46 processFile(request)
47 else:
48 send404(request)
49
50 def run(server_class=BaseHTTPServer.HTTPServer,
51 handler_class=MyHandler):
52 server_address = ('', 8000)
53 httpd = server_class(server_address, handler_class)
54 httpd.serve_forever()
55
56 run()