Python:在GET请求之后重置BaseHTTPRequestHandler的实例

时间:2018-01-25 23:17:01

标签: python python-3.x httpserver basehttprequesthandler

我有一个由python BaseHTTPRequestHandler类调用的HTTPServer类。基本上BaseHTTPRequestHandler只运行一个基本算法,然后响应Get请求。问题在于,每次执行Get请求时,我都会收到正确的响应,但BaseHTTPRequestHandler中收集的所有数据都会重置,就像每次请求发送到HTTPServer时一样创建BaseHTTPRequestHandler的新实例。我无法在网上找到真正解释幕后情况的内容。我附上了我的代码的简化版本。任何帮助或解释将不胜感激。

在任何人建议创建类或全局变量之前,我使用一个线程一次创建此类的多个实例,这样做会使每个线程上的所有实例共享并替换彼此的数据。

CODE(复制和粘贴时缩进)

BaseHTTPRequestHandler

此简化版仅跟踪已发生的警报数。问题是,当我调用Get请求时,计数总是重置为0,就好像重置了类的实例一样。

class SimulationServer(BaseHTTPRequestHandler):
def __init__(self, address, port, randomNumberMax, *args):
    self.IP_ADDRESS = address
    self.PORT = port
    self.RANDOM_NUMBER_MAX = randomNumberMax
    self.COUNT = 0
    BaseHTTPRequestHandler.__init__(self, *args)

def do_GET(self):
    if self.headers['Authorization'] == 'Basic ' + str(key):
        print("send response")
        self.do_HEAD()
        randomNumberMax = self.RANDOM_NUMBER_MAX
        response = ""

        if randint(0, randomNumberMax) == 0:
            self.generateAlert()

        base_path = urlparse(self.path).path
        print('base_path: ' + base_path)
        if base_path == '/count':
            response = self.getCount()

        self.wfile.write(bytes(response, 'utf-8'))

def getCount(self):
    count = self.COUNT
    jsonString = '{"_sig": "","count": ' + str(count) + '}'
    return jsonString

def generateAlert(self):
    newAlert = {}
    newAlert['siteId'] = "siteId"+ str(self.COUNT)
    newAlert['mesg'] = "Simulated Alert"
    newAlert['when'] = int(time.time())

    self.COUNT += 1

的HttpServer

class CustomHTTPServer(HTTPServer):
key = ''

def __init__(self, address, handlerClass=SimulationServer):
    super().__init__(address, handlerClass)

def set_auth(self, username, password):
    self.key = base64.b64encode(
        bytes('%s:%s' % (username, password), 'utf-8')).decode('ascii')

def get_auth_key(self):
    return self.key

主要

此类创建HTTPServer并附加handler

class RunSimulator(object):
def run(self, alertFrequency=50, port=9000):
    ipAddress="127.0.0.1"
    def handler(*args):
        SimulationServer(ipAddress, port, alertFrequency, *args)

    simulationServer = CustomHTTPServer((ipAddress, port), handler)
    simulationServer.set_auth('username', 'password')

    try:
        simulationServer.serve_forever()
    except KeyboardInterrupt:
        pass

    simulationServer.server_close()
    print(time.asctime(), "Server Stops - %s:%s" % (ipAddress, port))

if __name__ == "__main__":
    from sys import argv
    simu = RunSimulator()
    simu.run()

1 个答案:

答案 0 :(得分:2)

所以简短的回答是每次发送请求时都会创建一个新实例。

BaseHTTPServer.HTTPServerSocketServer.TCPServer的子类,它本身是SocketServer.BaseServer的子类。每次请求进入时,它都会处理请求process_request,然后调用finish_requestfinish_request将实例化您的请求处理程序的新实例。