Multithreading support for BaseHTTPServer

Steve Holden sholden at holdenweb.com
Tue Aug 28 10:49:22 EDT 2001


"Gerson Kurz" <gerson.kurz at t-online.de> wrote in message
news:3b8b7daf.699296734 at news.isar.de...
> 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?

import SocketServer
import BaseHTTPServer
import CGIHTTPServer

class ThreadingCGIServer(SocketServer.ThreadingMixIn,
                   BaseHTTPServer.HTTPServer):
    pass

import sys

server = ThreadingCGIServer(('', 8080), CGIHTTPServer.CGIHTTPRequestHandler)
#
try:
    while 1:
        sys.stdout.flush()
        server.handle_request()
except KeyboardInterrupt:
    print "Finished"

Mixin classes are usually designed to slot right in to an existing
framework. In this particular case, ThreadingMixin needs to be used with
classes which have a certain server structure. It provides methods for your
class which would otherwise be inherited from the later superclasses in the
inheritance list.

If BaseHTTPServer has everything you need, the above solution should be all
you require. If you aren't bothered about interrupting the server you could
just call serve_forever(). I remember when I frist came across the
*HTTPServer classes they seemed a lot more complex than they really are!

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list