Basic Web server in Python

#Copyright Jon Berg , turtlemeat.com

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import logging
import logging.config

logger = 0
PORT = 8080 # change this to suit your current test

class MyHandler(BaseHTTPRequestHandler):
	
    def do_GET(self):
        try:
            if self.path.endswith(".html"):
                logger.info('Path = '+self.path)
                f = open(curdir + sep + self.path) #self.path has /test.html
				#note that this potentially makes every file on your computer readable by the internet
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
                return
            if self.path.endswith(".esp"):   #our dynamic content
                logger.info('Path = '+self.path)
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write("hey, today is the" + str(time.localtime()[7]))
                self.wfile.write(" day in the year " + str(time.localtime()[0]))
                self.wfile.write("<br>")
                self.wfile.write("Time now is : "+time.strftime("%b, %d %Y %H:%M:%S"))
                return
            if self.path.endswith("/"):		# default to index.html
                logger.info('Path = /')
                f = open(curdir + sep + "index.html") #self.path has /test.html
				#note that this potentially makes every file on your computer readable by the internet
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(f.read())
                f.close()
                return
            if self.path.find("/callback") != -1:
                logger.info('Path = '+self.path)
                #print dir(self)
                #print self.requestline
                args = self.requestline
                if args.find('?') != -1:
                    opts = args.split(' ')[1][len("/callback?"):]
                    print opts
                else:
		    opts = 'no args'
		    print opts
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write("callback invoked<br>")
                self.wfile.write(opts)
                self.wfile.write("<br>")
                return
            if self.path.find("ProvisionerCallback.svc") != -1:
                logger.info('Path = ProvisionerCallback.svc')
                print('Path = ProvisionerCallback.svc')
                args = self.requestline
                onlyCmd = None
                print "Args="+args
                if args.find('?') != -1:
                    opts = args.split(' ')[1]
                    onlyCmd = opts.split('?')[1].split('&')
                    print onlyCmd
                else:
		    opts = 'no args'
                    print onlyCmd
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write("callback ProvisionerCallback.svc<br>")
                self.wfile.write(onlyCmd)
                self.wfile.write("<br>")
                return
        except IOError:
            self.send_error(404,'File Not Found: %s' % self.path)
     
    # def do_GET(self):
		# print "do_GET called"
		# args = self.requestline
		# if args.find('?') != -1:
			# print args.split(' ')[1][len("/callback?"):]
		# #print self.command
		# self.send_response(200)
		# self.end_headers()
		# self.wfile.write("<HTML>That's all folks!!!<BR><BR></html>");
		# 

    def do_POST(self):
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                query=cgi.parse_multipart(self.rfile, pdict)
            self.send_response(301)
            
            self.end_headers()
            upfilecontent = query.get('upfile')
            print "filecontent", upfilecontent[0]
            self.wfile.write("<HTML>POST OK.<BR><BR>");
            self.wfile.write(upfilecontent[0]);
            
        except :
            pass

def main():
    global logger
    logging.config.fileConfig('..\\py_logging.conf')
    moduleName = 'Web'
    logger = logging.getLogger(moduleName)
    try:
        server = HTTPServer(('', PORT), MyHandler)
        print 'started httpserver...'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received, shutting down server'
        server.socket.close()

if __name__ == '__main__':
    main()

Logging file config

# log.ini

[loggers]
keys=root

[handlers]
keys=default

[formatters]
keys=default

[logger_root]
level=INFO
handlers=default
qualname=(root) # note - this is used in non-root loggers
propagate=1 # note - this is used in non-root loggers
channel=
parent=

[handler_default]
class=handlers.TimedRotatingFileHandler
level=INFO
formatter=default
args=('web.log', 'H', 12)
filename=web.log

[formatter_default]
format=%(asctime)s %(pathname)s(%(lineno)d): %(levelname)s %(message)s
datefmt=
basicwebserver.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0