我将是第一个承认我仍然相对较新的Python的人。这个板子有很多帮助...
我正在开发一个项目,我正在使用多线程HTTP服务器,我需要将信号发送回主循环。我试图以此为基础:Passing a Queue to ThreadedHTTPServer
以下是我目前正在做的摘录(在Python 3.4中):
if __name__ == '__main__':
...
q1 = Queue(maxsize=0)
...
remote_http_thread = threading.Thread(target=remote_threader, args=(q1))
remote_http_thread.daemon = True
remote_http_thread.start()
...
while 1:
time.sleep(1)
try:
my_message = q1.get_nowait()
message_flag = 1
print("GOT THE FOLLOWING QUEUE MESSAGE :", my_message)
except:
message flag = 0
...
以下是另一个文件(我的HTTP服务器代码):
def remote_threader(qit):
remote_Server = ThreadedHTTPServer(("", 35677), P_Server)
remote_Server.qu = qit
remote_Server.serve_forever()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
class P_Server(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
self.qu = server.qu # save the queue here.
def go_GET(self):
...
# We have an event that we want to signal back to the main loop
self.qu.put("Event")
HTTP服务器工作正常,我现在正试图将消息传递回主循环,以便某些事件导致事情发生。运行上面的代码导致P_Server没有属性'qu'
的异常从测试中可以看出,我在 init 步骤中创建的任何属性(甚至是硬编码的数字或字符串)在“do_GET”部分中都不可用。
任何人都可以让我知道我在这里做错了什么,我可以更改它,以便主要部分将消息放入HTTP服务器类的队列中?
答案 0 :(得分:1)
尝试在调用
之前设置属性BaseHTTPRequestHandler.__init__()
所以代码变成......
def remote_threader(qit):
remote_Server = ThreadedHTTPServer(("", 35677), P_Server)
remote_Server.qu = qit
remote_Server.serve_forever()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
class P_Server(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
# THE ATTRIBUTE IS SET HERE
self.qu = server.qu # save the queue here.
# super's init called after setting attribute
BaseHTTPRequestHandler.__init__(self, request, client_address, server)
def go_GET(self):
...
# Accessed in GET
self.qu.put("Event")
当我在调用BaseHttpRequestHandler的init之前设置属性时,为我工作