Skip to content

Instantly share code, notes, and snippets.

@mmaloney
Created August 6, 2014 16:38
Show Gist options
  • Save mmaloney/7df3177b59bb0893e601 to your computer and use it in GitHub Desktop.
Save mmaloney/7df3177b59bb0893e601 to your computer and use it in GitHub Desktop.
Python Web Server
import sys, getopt
import SimpleHTTPServer, SocketServer
import datetime, time
import logging
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
open(logfile, "a").write("%s - - PythonWebApp - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("<html><h1>Hello World !</h1><h2>For more information on Zenoss Control Center, check out <a href='http://zenoss.io'>http://zenoss.io</a></h2> </html> ")
return
def main(argv):
# Init vars
port = 0
global logfile
logfile = ''
logconfig =''
# Parse CLI Args
try:
opts, args = getopt.getopt(argv,"h:p:l:",["port=","logfile="])
except getopt.GetoptError:
print 'webserver.py -p <port> -l <log file>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'webserver.py -p <port> -l <log file>'
sys.exit()
elif opt in ("-p", "--port"):
port=int(arg)
elif opt in ("-l", "--logfile"):
logfile = arg
if port == 0:
print 'invalid port specified'
sys.exit(2)
if logfile == '':
print 'no log file specified'
sys.exit(2)
# Set logging config
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s%(name)-12s%(levelname)-8s%(message)s',
datefmt='%m-%d %H:%M:%S',
filename=logfile,
filemode='w')
fh = logging.FileHandler(logfile)
#fh.setFormatter = ('%(asctime)s %(levelname)s %(message)s')
logger = logging.getLogger(' WWW')
logger.addHandler(fh)
try:
httpd = HTTPServer(('',port), SimpleHTTPRequestHandler)
# Log webserver startup
logger.debug('HTTP server started')
print '%s: HTTP server listening on TCP port: %d' % (datetime.datetime.now(),port)
# Log webserver config
logger.info('HTTP server listening on TCP port: %s',port)
logger.info('HTTP server logfile: %s',logfile)
# Run webserver as a long running process
httpd.serve_forever()
except getopt.GetoptError:
print exc.msg
sys.exit(2)
if __name__ == "__main__":
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment