Skip to content

Instantly share code, notes, and snippets.

@zeisss
Created September 16, 2010 15:19
Show Gist options
  • Save zeisss/582595 to your computer and use it in GitHub Desktop.
Save zeisss/582595 to your computer and use it in GitHub Desktop.
#Copyright Jon Berg , turtlemeat.com
# Modified by Stephan Zeissler, moinz.de
###
# Creates a simple webserver running on port 80
# Every request is logged into a request-<id>.log file containg the path, headers and body
# The response is always 200 and the content of the file response.txt
###
import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri
class MyHandler(BaseHTTPRequestHandler):
counter = 0
def do_GET(self):
try:
self.log_message("Writing request-" + str(MyHandler.counter) + ".log")
fpLog = open(curdir + sep + "requests" + sep + "request-" + str(MyHandler.counter) + ".log", "w")
MyHandler.counter = MyHandler.counter + 1
fpLog.write("%s %s %s\n" % (self.command, self.path, self.request_version))
list = self.headers.getplist()
for (k,v) in self.headers.items():
fpLog.write("%s: %s\n" % (k,v))
fpLog.write("\n")
fpLog.flush()
if ( self.command == 'POST'):
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
length = int(self.headers.getheader('content-length'))
if ctype == 'multipart/form-data':
self.body = cgi.parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
qs = self.rfile.read(length)
self.body = cgi.parse_qs(qs, keep_blank_values=1)
else:
self.body = self.rfile.read(length)
fpLog.write(str(self.body))
fpLog.flush()
fpLog.close()
# The response:
f = open(curdir + sep + "response.xml")
self.send_response(200)
self.send_header('Content-Type', 'text/xml')
self.end_headers()
self.wfile.write(f.read())
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self):
self.do_GET()
def main():
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment