我必須將參數傳遞給SimpleHTTPRequestHandler類,因此我使用類工廠創建瞭如下的自定義處理程序。將參數傳遞給SimpleHTTPRequestHandler
def RequestHandlerClass(application_path):
class CustomHandler(SimpleHTTPRequestHandler):
def __init__(self, request, client_address, server):
SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
self._file_1_done = False
self._file_2_done = False
self._application_path = application_path
def _reset_flags(self):
self._file_1_done = False
self._file_2_done = False
def do_GET(self):
if (self.path == '/file1.qml'):
self._file_1_done = True
if (self.path == '/file2.qml'):
self._file_2_done = True
filepath = self._application_path + '/' + self.path # Error here
try:
f = open(filepath)
self.send_response(200)
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError as e :
self.send_error(404,'File Not Found: %s' % self.path)
if (self._file_1_done and self._file_2_done):
self._reset_flags()
self.server.app_download_complete_event.set()
return CustomHandler
這是使用自定義的處理
class PythonHtpServer(BaseHTTPServer.HTTPServer, threading.Thread):
def __init__(self, port, serve_path):
custom_request_handler_class = RequestHandlerClass(serve_path)
BaseHTTPServer.HTTPServer.__init__(self, ('0.0.0.0', port), custom_request_handler_class)
threading.Thread.__init__(self)
self.app_download_complete_event = threading.Event()
def run(self):
self.serve_forever()
def stop(self):
self.shutdown()
我的httpserver,我開始與
http_server = PythonHtpServer(port = 8123, serve_path = '/application/main.qml')
服務器啓動服務器,但我得到這個錯誤
AttributeError: CustomHandler instance has no attribute '_application_path'
基本上,從錯誤,服務器確實開始,但我不知道爲什麼它不創建屬性(或者init沒有被調用)。請告訴我我哪裏錯了。任何幫助將受到歡迎。