0

I have a simple HTTP server

import http.server
import socketserver
import os
import threading
import time

from queue import Queue


PORT = 8005

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, directory=None, **kwargs):
        self.active_threads = []        
        super().__init__(*args, directory=None, **kwargs)

    def do_GET(self):
        person_ids = self.path[1:].split(',')
        print("Handle request", person_ids)
        print(f"active_threads_id, {id(self.active_threads)}")
        

# Create an object of the above class
handler_object = MyHttpRequestHandler
my_server = socketserver.TCPServer(("", PORT), handler_object)
# Star the server
my_server.serve_forever()

I want to have self.active_threads = [] as shared (single) object for all requests. But output shows that each request has it's own object. See output of the program

Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238782272
Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238809984
Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238809280
Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238782272

I want output like below:

Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238782272 # the same id
Handle request ['qwert2', 'qwert3']
active_threads_id, 140470238782272 # the same id
0

1 Answer 1

1

You can make active_threads a class attribute:

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    active_threads = []

    def __init__(self, *args, directory=None, **kwargs):
        super().__init__(*args, directory=None, **kwargs)

    def do_GET(self):
        person_ids = self.path[1:].split(',')
        print("Handle request", person_ids)
        print(f"active_threads_id, {id(self.active_threads)}")

Prints:

Handle request ['a', 'b']
active_threads_id, 1680095513280
Handle request ['a', 'b']
active_threads_id, 1680095513280
Handle request ['a', 'b']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
Handle request ['c', 'd']
active_threads_id, 1680095513280
. . . etc.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.