根据源代码,BaseServer.shutdown()必须从与运行服务器不同的线程调用。
不过,我正在试图closures服务器在Web请求中提供给服务器的特定值。
请求处理程序显然运行在这个线程,所以它会仍然死锁后,我已经这样做了:
httpd = BaseHTTPServer.HTTPServer(('', 80), MyHandler) print("Starting server in thread") threading.Thread(target=httpd.serve_forever).start()
我怎样才能做到我想要的? 我必须设置一个套接字或pipe道或什么东西(请告诉我如何做到这一点,如果是解决scheme),主线程可以阻止和等待子线程发送消息,在这一点上,将能够调用shutdown()?
我目前能够通过从请求处理程序中调用“httpd.socket.close()”来实现某种“作品”行为。 这会生成一个[Errno 9] Bad file descriptor
错误,似乎终止Windows上的进程。
但是,这显然不是正确的方法。
更新约。 2013年8月我已经利用node.js来满足强大的asynchronousI / O需求,但是大量的副项目(例如线性代数研究,各种命令行工具前端)让我回到python。 回顾一下这个问题,BaseHTTPServer可能相对于其他选项(如Phil提到的各种微框架)来说可能没有多less实用价值。
threading.Event对于发送其他线程很有用。 例如,
please_die = threading.Event() # in handler please_die.set() # in main thread please_die.wait() httpd.shutdown()
如果要在线程之间发送数据,则可以使用队列 。
1.来自BaseHTTPserver文档
要创建一个不会永远运行的服务器,但要满足一些条件:
def run_while_true(server_class=BaseHTTPserver.HTTPserver, handler_class=BaseHTTPserver.BaseHTTPRequestHandler): """ This assumes that keep_running() is a function of no arguments which is tested initially and after each request. If its return value is true, the server continues. """ server_address = ('', 8000) httpd = server_class(server_address, handler_class) while keep_running(): httpd.handle_request()
允许一些URL调用来设置条件终止,使用任何罢工你的幻想那里。
编辑 : keep_running
是你选择的任何功能,可以像这样简单:
def keep_running(): global some_global_var_that_my_request_controller_will_set return some_global_var_that_my_request_controller_will_set
你可能想要一些更聪明的和without_rediculously_long_var_names
。
2. BaseHTTPserver通常比你想要的要低。 有许多微型框架可能适合您的需求