passing context into BaseHTTPRequestHandler

Bernhard Herzog bh at intevation.de
Fri Mar 23 20:19:22 CET 2012


Steve Howell <showell30 at 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()


   Bernhard


-- 
Bernhard Herzog  |  ++49-541-335 08 30  |  http://www.intevation.de/
Intevation GmbH, Neuer Graben 17, 49074 Osnabrück | AG Osnabrück, HR B 18998
Geschäftsführer: Frank Koormann, Bernhard Reiter, Dr. Jan-Oliver Wagner



More information about the Python-list mailing list