2013-01-11 02:57:43 +01:00
|
|
|
from __future__ import print_function
|
2013-08-12 19:23:57 +01:00
|
|
|
import os
|
2013-03-16 19:29:10 +01:00
|
|
|
import sys
|
2013-08-12 19:23:57 +01:00
|
|
|
import logging
|
2013-01-11 02:57:43 +01:00
|
|
|
try:
|
|
|
|
|
import SimpleHTTPServer as srvmod
|
|
|
|
|
except ImportError:
|
2013-03-03 20:12:31 -08:00
|
|
|
import http.server as srvmod # NOQA
|
2013-01-11 02:57:43 +01:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
import SocketServer as socketserver
|
|
|
|
|
except ImportError:
|
2013-03-03 20:12:31 -08:00
|
|
|
import socketserver # NOQA
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2013-07-07 12:44:21 +02:00
|
|
|
PORT = len(sys.argv) == 2 and int(sys.argv[1]) or 8000
|
2013-12-04 22:26:39 +11:00
|
|
|
SUFFIXES = ['', '.html', '/index.html']
|
|
|
|
|
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2013-08-12 19:23:57 +01:00
|
|
|
class ComplexHTTPRequestHandler(srvmod.SimpleHTTPRequestHandler):
|
|
|
|
|
def do_GET(self):
|
|
|
|
|
# we are trying to detect the file by having a fallback mechanism
|
2013-12-04 22:26:39 +11:00
|
|
|
found = False
|
2013-08-12 19:23:57 +01:00
|
|
|
for suffix in SUFFIXES:
|
|
|
|
|
if not hasattr(self,'original_path'):
|
|
|
|
|
self.original_path = self.path
|
|
|
|
|
self.path = self.original_path + suffix
|
|
|
|
|
path = self.translate_path(self.path)
|
|
|
|
|
if os.path.exists(path):
|
2013-12-04 22:26:39 +11:00
|
|
|
srvmod.SimpleHTTPRequestHandler.do_GET(self)
|
|
|
|
|
logging.info("Found: %s" % self.path)
|
|
|
|
|
found = True
|
2013-08-12 19:23:57 +01:00
|
|
|
break
|
2014-07-22 11:48:15 -04:00
|
|
|
logging.info("Tried to find file %s, but it doesn't exist. ", self.path)
|
2013-12-04 22:26:39 +11:00
|
|
|
if not found:
|
2014-07-22 11:48:15 -04:00
|
|
|
logging.warning("Unable to find file %s or variations.", self.path)
|
2013-08-12 19:23:57 +01:00
|
|
|
|
|
|
|
|
Handler = ComplexHTTPRequestHandler
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2014-02-13 15:46:33 -08:00
|
|
|
socketserver.TCPServer.allow_reuse_address = True
|
2013-03-16 19:29:10 +01:00
|
|
|
try:
|
|
|
|
|
httpd = socketserver.TCPServer(("", PORT), Handler)
|
|
|
|
|
except OSError as e:
|
2014-07-22 11:48:15 -04:00
|
|
|
logging.error("Could not listen on port %s", PORT)
|
2013-03-16 19:29:10 +01:00
|
|
|
sys.exit(getattr(e, 'exitcode', 1))
|
|
|
|
|
|
2013-01-11 02:57:43 +01:00
|
|
|
|
2014-07-22 11:48:15 -04:00
|
|
|
logging.info("Serving at port %s", PORT)
|
2013-03-19 12:15:58 +01:00
|
|
|
try:
|
|
|
|
|
httpd.serve_forever()
|
|
|
|
|
except KeyboardInterrupt as e:
|
2014-07-22 11:48:15 -04:00
|
|
|
logging.info("Shutting down server")
|
2013-12-04 22:26:39 +11:00
|
|
|
httpd.socket.close()
|