BaseHTTPServer and class variables

Eddie Corns eddie at holyrood.ed.ac.uk
Mon Jan 26 12:33:42 EST 2004


yin_12180 at yahoo.com (Yin) writes:

>Hello.

>I am using the basehttpserver to implement the HTTP protocol to serve
>a fairly large lexicon that I have loaded as a dictionary in python. 
>Rather than writing a whole server, I would like to reuse the
>BaseHTTPserver classes. I am interested in finding a way to serve the
>dict without loading the whole dict into memory everytime an HTTP
>request is made. The dict lives in local memory when it is loaded and
>takes a long time to load.

>Unfortunately with the basehttpserver.httpserver and
>basehttpserver.requesthandlerclass, I am not finding it easy to define
>a method to load the dict initially.  Any thoughts are appreciated.

>Ideally, in a do_GET for the requesthandlerclass, it'd be nice to be
>able to access the dict as a class variable, but this doesn't work for
>me.

import BaseHTTPServer

class Serv (BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET (self):
        path = self.path.strip('/').split('/')
        self.send_response (200)
        self.send_header ('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write (self.dict[path[-1]])

# load dictionary
D={'foo':1, 'bar':2}
server = BaseHTTPServer.HTTPServer (('', 8080), Serv)
server.RequestHandlerClass.dict = D
server.serve_forever()

Possibly not the best way but it should do unless someone less lazy than I
responds.  (Assuming I'm understanding your request correctly).

Eddie



More information about the Python-list mailing list