473,796 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code feedback

Hi, all I would like some feedback on a multithreaded HTTP server I've
written. The server serves python-scripts by dynamically loading scripts
in the same directory as itself. When a request is made to one of these
scripts the script is executed and its output is returned to the
requester.

Here is the server code, HTTPServer.py:

# Basic, threaded HTTP server, serving requests via python scripts
# Author: Tor Erik Soenvisen

# Std lib imports
import BaseHTTPServer, os, threading, Queue

class HTTPServer(Base HTTPServer.HTTP Server):
""" A threaded HTTP server """

port = 80
# Maximum requests on hold
request_queue_s ize = 250
# Maximum requests serviced concurrently
workers = 20

def __init__(self, port=None, reqSize=None, workers=None):

if port is not None: self.port = port
if reqSize is not None: self.request_qu eue_size = reqSize
if workers is not None: self.workers = workers

self.sharedPath = os.path.dirname (os.path.abspat h(__file__))
# self.sharedPath must be set before calling self.getHandler s
self.handler = self.getHandler s()
self.jobQueue = Queue.Queue(sel f.request_queue _size)
addr = ('', self.port)
BaseHTTPServer. HTTPServer.__in it__(self, addr,
HTTPRequestHand ler)

# Exit threads when application exits
self.daemon_thr eads = True

self.createThre adPool()
self.serve_fore ver()

def getHandlers(sel f):
""" Imports all python scripts in the current directory except
this one.
These scripts are the response generators corresponding to
all valid
path requests. The idea is to comprise something similar to
a
lightweight CGI, where each script generate HTTP responses
to HTTP requests
"""
import inspect
# 1. List all files in current directory
# 2. Skip files not having a .py extension, in addition to this
file
# 3. Slice of .py extension
handler = dict.fromkeys([x[:-3] for x in os.listdir
(self.sharedPat h) \
if x.endswith('.py ') and \
x != os.path.basenam e(__file__)])
for name in handler:
handler[name] = __import__(name )
# Make sure the handler contains a run function accepting at
least
# one parameter
if not hasattr(handler[name], 'run') or \
len(inspect.get argspec(handler[name].run)[0]) != 2:
print 'Handler %s.py dropped because it lacks ' % name +
\
'a function named run accepting two arguments'
del handler[name]

return handler

def createThreadPoo l(self):
""" Creates pool of worker threads, servicing requests """
self.tpool = []
for i in range(self.work ers):
self.tpool.appe nd(threading.Th read
(target=self.pr ocess_request_t hread,
args=()))
if self.daemon_thr eads:
self.tpool[-1].setDaemon(1)
self.tpool[-1].start()

def serve_forever(s elf):
""" Handle requests "forever" """
while 1:
self.handle_req uest()

def process_request (self, request, client_address) :
""" Task source: dispath requests to job queue """
self.jobQueue.p ut((request, client_address) )

def process_request _thread(self):
""" Task sink: process requests from job queue """
while 1:
request, client_address = self.jobQueue.g et()
try:
self.finish_req uest(request, client_address)
self.close_requ est(request)
except:
self.handle_err or(request, client_address)
self.close_requ est(request)

class HTTPRequestHand ler(BaseHTTPSer ver.BaseHTTPReq uestHandler):
""" Handles HTTP requests. GET is the only method currently
supported """

# Set HTTP protocol version 1.1
protocol_versio n = 'HTTP/1.1'
# Set default response headers
responseHeaders = {'Content-Type': 'text/html',
'Content-Length': '',
'Connection': 'close'}

def log_message(sel f, format, *args):
""" Log function: see BaseHTTPServer. py for info on arguments
"""
pass

def do_GET(self):
""" Handles HTTP GET requests """

name = self.path.lstri p('/')
try:
handler = self.server.han dler[name].run
except KeyError:
self.send_error (code=404, message='File %s not found' %
name)
else:
data = handler(self.he aders, self.responseHe aders)
# Set Content-Length header
self.responseHe aders['Content-Length'] = str(len(data))
# Send headers and content
self.send_respo nse(200, message='OK')
for name, value in self.responseHe aders.items():
self.send_heade r(name, value)
self.end_header s()
self.wfile.writ e(data)

if __name__ == '__main__':
""" For testing purposes """
HTTPServer(port =8081)
Pointing the browser to http://localhost:8081/index yields Hello, world!
when the script index.py is contained in the same directory as the
server.

index.py:

def run(request, response):
""" Entrypoint function, called by web-server
Argument request is the request headers as a mimetools.Messa ge
instance, while response is a dictionary containing the default
response headers.
"""
html = '<html><head><t itle></title></head><body>Hell o, world!</body>
</html>'
return html

Suggestions for making the server faster, more secure, more general,
and/or more compact will be appreciated.

Regards, Tor Erik

PS: Yes, I know there exist heaps of web-servers out there.
Nov 17 '06 #1
0 1128

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2097
by: Dafella | last post by:
The following is code from Xeoport. It is suppose to access my pop3 account and load email into Mysql database. It's not inserting and there is no log or anything to tell me why. Here is the page. http://www.dafella.com/xeoport/ The original coder left no contact info. The reason I think it's the code is because of another issue.
26
2945
by: Michael Strorm | last post by:
Hi! I posted a message a while back asking for project suggestions, and decided to go with the idea of creating an adventure game (although it was never intended to be a 'proper' game, rather an excuse to write- and learn- some C++). To cut a long story short, I wrote a fair chunk of it, but realised that it's... not very good. Okay, it's my first "proper" C++ program, so that's no big deal, but I don't want to waste more time working...
2
2490
by: Sergio del Amo | last post by:
Hi, I wrote some functionality for a Web Page with Javascript. My code works perfectly for Firefox but not for IE. I become some errors apparently all based in the same problem wich scapes to my knowledge. If anyone can help me, i would be really grateful. These are the errors i was speaking about: -------------------------------------------- Line: 58
2
2595
by: Kavitha Rao | last post by:
Hi, I am getting the following errors while trying to run this snippet in Microsoft Visual C++.Can't seem to print the crc value stored. /* +++Date last modified: 05-Jul-1997 */ /* Crc - 32 BIT ANSI X3.66 CRC checksum files */ #include <stdio.h> #include "crc.h"
192
9532
by: Vortex Soft | last post by:
http://www.junglecreatures.com/ Try it and tell me what's happenning in the Microsoft Corporation. Notes: VB, C# are CLS compliant
1
1149
by: Terry Olsen | last post by:
No offense to anyone in this group, particularly Tom Shelton, Michael M, or Newbie Coder. But who the hell is Crouchie1998 and why is he accusing every submission I make to Planet Source Code to be plagiarized? In one submission to retrieve the XP key using native .NET function instead of the API, he said I copied the code from him when I clearly gave credit to the original authors of the API code and said that I had removed the API...
2
1210
by: DrNoose | last post by:
Hi! I'm working on code for a feedback form. I want the data from the user that is taken from the form to be emailed back to me. I'm using vb with visual studios 2005. I have most of the code, but have some missing stuff, because I'm not totally sure what I'm doing! Can someone take a look at this code and tell me what I'm missing.
9
2503
by: gs | last post by:
the feedback for the install of c#2008 places 97 to 99% cpu load for way too long on athlon x64 3800+ PC. 3/4 an hour later its only about 80% complete, continuing with 98% CPU load! Next time installing visual studio /dot product I will likely make sure no feedback
27
2969
by: George2 | last post by:
Hello everyone, Should I delete memory pointed by pointer a if there is bad_alloc when allocating memory in memory pointed by pointer b? I am not sure whether there will be memory leak if I do not delete a. try { a = new int ;
8
2154
by: Brian | last post by:
What's the best way to debug code that is being run during garbage collection? We are getting AccessViolationExceptions that seem to be happening during garbage collection. But when it hits the debugger, it is at whatever line of code the main thread was at when the garbage collector decided to run. In other words, the debugger is in irrelevant code. In general, if you have bugs in Dispose or finalization methods, what's the best...
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10221
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10169
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9050
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.