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:
- Create a brand new
threading.local
- Store a reference to it in the variable
global_data
- Give it a
token
- Create a brand new
threading.local
- 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}
?