passing context into BaseHTTPRequestHandler

Steve Howell showell30 at yahoo.com
Fri Mar 23 14:58:17 EDT 2012


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()
Basically, it takes five lines of code just to pass context into the
handler:
 def handler(*args):
 MyHandler(context, *args)
 def __init__(self, context, *args):
 self.context = context
 BaseHTTPRequestHandler.__init__(self, *args)
Typically the second argument to HTTPServer is a subclass of
BaseHTTPRequestHandler, but I pass in "handler" instead, which
instantiates a new instance of MyHandler with the context from the
enclosing scope. At first I tried to say "MyHandler(*args).context =
context", but that assignment was too late, because
BaseHTTPRequestHandler.__init__ does a lot of stuff during the
construction phase. That's what forced me to write my own custom
__init__ as well.
I hope there's enough info here to understand what I'm trying to
achieve, but if it helps to see my code in more context, you can see
it here:
 https://gist.github.com/2173618
Thanks.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /