Python 许多请求的 HTTP 服务器共享对象

Python HTTP server shared object for many requests

我有一个简单的 HTTP 服务器

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()

我想 self.active_threads = [] 作为所有请求的共享(单个)对象。 但输出显示每个请求都有自己的对象。查看程序的输出

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

我想要如下输出:

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

您可以将 active_threads 设为 class 属性:

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)}")

打印:

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.