How to change variables in a SocketServer server instance from an instance of the RequestHandler handler in Python?

Here is the code in question:

  class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
     __slots__ = ("loaded")

  class Handler(SocketServer.StreamRequestHandler):
     def handle(self):
        print self.server.loaded # Prints "False" at every call, why?
        self.server.loaded = True
        print self.server.loaded # Prints "True" at every call, obvious!

  server = Server(('localhost', port), Handler)
  server.loaded = False

  while True:
     server.handle_request()

Every time a new request arrives, I get the output False, which follows True. I want False, and then Truefor the first time True, and then True.

Why not the changes made to the variable in the server instance, which is saved outside the handler function handle()?

UPDATED:

So, I'm trying to use global variables to achieve what I want:

  loaded = False

  class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer):
     pass

  class Handler(SocketServer.StreamRequestHandler):
     def handle(self):
        global loaded
        print loaded # Prints "False" at every call still, why?
        loaded = True
        print loaded # Prints "True" at every call, obvious!

  def main():
     server = Server(('localhost', 4444), Handler)
     global loaded
     loaded = False

     while True:
        server.handle_request()

  if (__name__ == '__main__'):
     main()

And it still does not work, i.e. produces the same result as before. Can someone tell me where I am going wrong?

+3
2

Forking , . ThreadingTCPServer:

import SocketServer

class Server(SocketServer.ThreadingTCPServer):
    __slots__ = ("loaded")

class Handler(SocketServer.StreamRequestHandler):
    def handle(self):
        self.server.loaded = not self.server.loaded
        print self.server.loaded # Alternates value at each new request now.

server = Server(('localhost',5000),Handler)
server.loaded = False

while True:
    server.handle_request()
+3

, SocketServer.ForkingMixin . , , reset . , , self.server.loaded, reset . .

, , - , er, persistent =). , , . , , . , SocketServer Python.

Google : "filetype: py SocketServer ForkingMixIn" ( - CherryPy, ).

+2

Source: https://habr.com/ru/post/1768147/


All Articles