Currently, I am writing some python program for the front of our storage system. By using ‘BaseHTTPRequestHandler’ and ‘ThreadedHTTPServer’, we could implement a simple multi-thread http server quickly. But after add ‘__init__()’ for our ‘MyHandler’, it doesn’t work correctly now:
class MyHandler(BaseHTTPRequestHandler):
def __init__(self):
self.request_id = ''
Then I found this statement in python docs:
Subclasses should not need to override or extend the __init__() method.
But thanks for the code example, we could override ‘__init__’ of BaseHTTPRequestHandler’ this way:
class MyHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.request_id = ''
Hello.
You have to invert the 2 lines in your __init__, otherwise you’ll face the following error when you’ll try to use request_id in other methods during the first request handled:
AttributeError: MyHandler instance has no attribute ‘request_id’
So:
class MyHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
self.request_id = ”
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
This is because BaseHTTPRequestHandler.__init__(…) does NOT exit until a first request has been handled… So, your attribute is not created yet during the first request…
Regards,
Daniel