On Mar 23, 12:19 pm, Bernhard Herzog <b...@intevation.de> wrote: > Steve Howell <showel...@yahoo.com> writes: > > I have a use case where I'm running BaseHTTPServer.HTTPServer, and I > > want to configure the request handler with some context. I've gotten > > the code to work, but it feels overly heavy. I am wondering if > > anybody could suggest an easier idiom for this. > > > This is a brief sketch of the code: > > > class MyHandler(BaseHTTPRequestHandler): > > def __init__(self, context, *args): > > self.context = context > > BaseHTTPRequestHandler.__init__(self, *args) > > > def do_GET(self): > > // self.context will be available here > > > context = { .... } > > def handler(*args): > > MyHandler(context, *args) > > > server = HTTPServer(('', port), handler) > > server.serve_forever() > > You could store the context in the server object and access it in the > handler methods via self.server.context. It basically works like this: > > class MyHTTPServer(HTTPServer): > > def __init__(self, *args, **kw): > HTTPServer.__init__(self, *args, **kw) > self.context = { .... } > > class MyHandler(BaseHTTPRequestHandler): > > def do_GET(self): > context = self.server.context > ... > > server = MyHTTPServer(('', port), MyHandler) > server.serve_forever() >
Thanks for the suggestion. I made the change, and I think the code's a bit easier to read now. -- http://mail.python.org/mailman/listinfo/python-list