PDA

View Full Version : Making a python webserver



bobng
10-23-2008, 11:02 PM
So I found some code to make a Python webserver. I modified it a tiny bit, and here it is. Its pretty fast as well (Could someone link me to some webserver software benchmarks?).

I ran a benchmark program that spawned 30 threads and just DDOSed the server with queries (Download any old webpage - the larger the better - and shove it as test.htm in the working directory), and no request took over 0.02 seconds.

Code:

#Copyright Jon Berg , turtlemeat.com

import string,cgi
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
#import pri

class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path == '/' or '':
f = open(curdir + sep + '/index.html')
else:
f = open(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()
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)

def do_POST(self):
global rootnode
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():
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()



Benchmark - Unstable:

import urllib
import threading
import time


class tester(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
while True:
try:
a = time.time()
z = urllib.urlopen('http://[YOUR IP HERE]/test.htm').read()
b = time.time()
print 'Time taken = %s'%(str(b-a))
#count = count + 1
#print str(count)
except:
pass

def main():
count = 0
for q in range(20):
a = tester()
a.start()

if __name__ == '__main__':
main()