I have a subclass of BaseHHTPRequestHandler which uses a dictonary "paths" and a function "api_call" which are defined in the main namespace of the module. I'd rather I was able to pass these object to the constructor and store them as data attributes "self.paths" and "self.api_call" but I'm not sure how to do that properly. My understanding is that one may extend a constructor by defining it's __init__ method, calling the parents constructor and then adding ones own attributes to taste. What I don't understand is where or how I am supposed to get these extra constructor arguments into the class given that I don't instantiate it myself, it is seemingly instantiated by HTTPServer class that I pass it to e.g.

httpd = HTTPServer(server_address, PlainAJAXRequestHandler)

I wondered if I ought to instantiate an instance of PlainAJAXRequestHandler, set the attributes (either manually or by extending it's constructor) and pass that to HTTPServer but I figured it expects a class not an instance as it probably wants to spawn one instance for each request so that would be a non starter. Might I need to subclass HTTPServer, find the bit that instantiates the request handler and override that so it passes it's constructor more parameters? Right now I'm pretty confused, can somebody please tell me how I might accomplish this, what I'm failing to grasp or point me to the docs that explain it - I've spent the last hour or two plowing through docs to no avail, I guess it's a case of keyword ignorance on my part! Code follows...

Thanks for reading!

Roger.



class PlainAJAXRequestHandler(BaseHTTPRequestHandler):

    paths = { "/": pages.main,
              "/jqtest/": pages.jqtest
            }

    def do_GET(self):

        # Handle JSON api calls
        if self.path[:6] == "/ajax?":
            getvars = urlparse.parse_qs( self.path[6:] )
            api_key = getvars[ "api" ][0]
            json_string = getvars[ "qry" ][0]
            json_object = json.loads( json_string )
            response = api_call( api_key, json_object )
            if response:
                self.send_response(200)
                self.send_header("Content-type", "application/json")
                self.end_headers()
                self.wfile.write( response )
            else:
                self.send_response(404)
                self.end_headers()
            return

        # Handle web pages
        try:
            page = self.paths[self.path]()
        except KeyError:
            self.send_response(404)
            self.end_headers()
            self.wfile.write( "404 - Document not found!" )
            return
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write( page )
        return
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to