#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import cgi
import time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
class HttpHandler( BaseHTTPRequestHandler ):
def __init__( self, request, client_address, server ):
self.handlers = {
'html': self.serve_html,
'htm': self.serve_html,
'txt': self.serve_text,
'py': self.serve_text,
}
BaseHTTPRequestHandler.__init__( self, request, client_address, server )
def do_GET( self ):
try:
endswith = self.path.split('.')[-1]
if endswith in self.handlers.keys():
handler = self.handlers[ endswith ]
handler()
except IOError:
self.send_error( 404, 'File Not Found: %s' % self.path )
def serve_html( self ):
f = open( '%s%s%s' % ( curdir, sep, self.path ) )
self.send_response( 200 )
self.send_header( 'Content-type', 'text/html' )
self.end_headers()
self.wfile.write( f.read() )
f.close()
def serve_text( self ):
f = open( '%s%s%s' % ( curdir, sep, self.path ) )
self.send_response( 200 )
self.send_header( 'Content-type', 'text/plain' )
self.end_headers()
self.wfile.write( f.read() )
f.close()
pass
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
def main( args ):
try:
server = ThreadedHTTPServer( ( '', 8080 ), HttpHandler )
print 'Starting server on port 8080'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main( sys.argv[1:] )