Multithreading support for BaseHTTPServer
Scherer, Bill
Bill.Scherer at VerizonWireless.com
Tue Aug 28 08:03:53 EDT 2001
Try the following:
-----------------------------------------------------------
import BaseHTTPServer, SocketServer, os
PORT = 9999
class ThreadingHTTPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer, BaseHTTPServer.HTTPServer):
pass
class
SampleRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def log_request(self, code='-', size='-'):
'''
The default log_request is not safe (it blocks)
under heavy load. I suggest using a Queue and another
thread to read from the queue and write it to disk as a
possible solution here. A pass works for now, but you
get no logging. Comment this method out to enable
(unsafe) logging.
'''
pass
def do_GET(self):
if self.path in ('', '/', 'HTTP/1.0'):
# return the PID, which (on Linux anyway) is
# different for each thread.
response = "This page served by thread with PID %s." % os.getpid()
self.send_response(200)
self.send_header("Content-type", 'text/plain')
self.end_headers()
self.wfile.write(response)
else:
self.send_response(404)
self.send_header("Content-type", 'text/plain')
self.end_headers()
self.wfile.write("Error 404: Not Found!")
def do_POST(self):
self.send_response(400)
self.send_header("Content-type", 'text/plain')
self.end_headers()
self.wfile.write("400: Bad Request")
def run(server_class=ThreadingHTTPServer, handler_class=SampleRequestHandler):
server_address = ('', PORT)
httpd = server_class(server_address, handler_class)
print 'serving on port', PORT
httpd.serve_forever()
if __name__ == '__main__':
run()
-----------------------------------------------------------------
On Tue, 28 Aug 2001, Gerson Kurz wrote:
> I'm using a BaseHTTPServer to serve up data dynamically. Some pages
> take time to process, so I would like to make a multithread server
> where serving up one page doesn't block any other.
>
> Looking into SocketServer.py, I found that both ThreadingTCPServer and
> ForkingTCPServer are available. However, when changing
>
> class HTTPServer(SocketServer.TCPServer):
>
> to
>
> class HTTPServer(SocketServer.ThreadingTCPServer):
>
> in BaseHTTPServer, I get an error
>
> File "D:\Python21\Lib\BaseHTTPServer.py", line 262, in handle
> self.raw_requestline = self.rfile.readline()
> File "d:\python21\lib\socket.py", line 233, in readline
> new = self._sock.recv(self._rbufsize)
> AttributeError: 'int' object has no attribute 'recv'
>
> Any ideas? Any simple method of multithreading BaseHTTPServer?
>
--
Bill.Scherer at Verizon Wireless
RHCE 807101044903581
More information about the Python-list
mailing list