Home > Back-end >  AttributeError: '_thread._local' object has no attribute 'token'
AttributeError: '_thread._local' object has no attribute 'token'

Time:07-23

There are already questions that address this problem, e.g.

Python: 'thread._local object has no attribute 'todo'

But the solutions doesn't seem to apply to my problem. I make sure to access threding.local() in the same thread that sets the value. I'm trying to use this feature in conjuction with socket server. This is my code

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        token = str(uuid4())
        global_data = threading.local()
        global_data.token = token
        logger.info(f"threading.local().token: {threading.local().token}")  # This line raises the error

The server code I'm using:

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


def run_server():
    server = ThreadedTCPServer(
        (definitions.HOST, definitions.PORT), ThreadedTCPRequestHandler
    )
    with server:
        server.serve_forever()

CodePudding user response:

Your code does this:

  1. Create a brand new threading.local
  2. Store a reference to it in the variable global_data
  3. Give it a token
  4. Create a brand new threading.local
  5. Print its token

Step 5 throws an exception because the new threading.local you created in step 4 does not have a token because it is not the same threading.local you created in step 1.

Perhaps you meant {global_data.token}?

  • Related