我必须将一个参数传递给 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)。请告诉我哪里出错了。欢迎任何帮助。
请您参考如下方法:
恕我直言,最简单的方法是使 _application_path 成为类的静态属性。它仅在类声明时声明,并且可以被类的实例透明地使用:
def RequestHandlerClass(application_path):
class CustomHandler(SimpleHTTPRequestHandler):
_application_path = application_path # static attribute
def __init__(self, request, client_address, server):
SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
self._file_1_done = False
self._file_2_done = False
def _reset_flags(self):
...
这样,自定义处理程序类的每个新实例都可以作为 self._application_path 访问应用程序路径。
