passing arguments to tcpserver classes

Eric Spaulding els24 at cornell.edu
Mon Jun 18 17:04:29 EDT 2007


Great -- thanks! (and also to J. Ezequiel).

Mark T wrote:
> "Eric Spaulding" <els24 at cornell.edu> wrote in message 
> news:mailman.9058.1181745026.32031.python-list at python.org...
>   
>> Is there an easy way to pass arguments to a handler class that is used by 
>> the standard TCPServer?
>>
>> normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass)
>>
>> I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), 
>> TCPHandlerClass, (arg1,arg2))
>>
>> And have arg1, arg2 available via TCPHandlerClass.__init__ or some other 
>> way.
>>
>> Where TCPHandlerClass:
>>
>> class TCPHandlerClass(SocketServer.StreamRequestHandler):
>>    def handle(self):
>>       #handle stream events here#
>>
>>
>> Thanks for any advice.
>>
>>     
>
> In the handler class, self.server refers to the server object, so subclass 
> the server and override __init__ to take any additional server parameters 
> and store them as instance variables.
>
> import SocketServer
>
> class MyServer(SocketServer.ThreadingTCPServer):
>     def __init__(self, server_address, RequestHandlerClass,arg1,arg2):
>         SocketServer.ThreadingTCPServer.__init__(self,server_address,RequestHandlerClass)
>         self.arg1 = arg1
>         self.arg2 = arg2
>
> class MyHandler(SocketServer.StreamRequestHandler):
>     def handle(self):
>         print self.server.arg1
>         print self.server.arg2
>
> if __name__ == '__main__':
>     srv = MyServer(('',5000),MyHandler,123,456)
>     srv.serve_forever()
>
> --Mark
>
>   

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070618/9797fdff/attachment.html>


More information about the Python-list mailing list