我必须将参数传递给 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
这是我使用自定义处理程序的 httpserver
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()
我启动服务器
http_server = PythonHtpServer(port = 8123, serve_path = '/application/main.qml')
服务器启动,但我收到此错误
AttributeError: CustomHandler instance has no attribute '_application_path'
基本上,从错误开始,服务器确实启动了,但我不知道为什么它没有创建属性(或者没有调用 init)。请告诉我哪里出错了。欢迎任何帮助。