如何在BaseHTTPRequestHandler子类中停止BaseHTTPServer.serve_forever()?
-
06-07-2019 - |
题
我在一个单独的线程中运行我的 HTTPServer
(使用无法停止线程的线程模块......)并且希望在主线程也关闭时停止提供请求。 / p>
Python文档声明 BaseHTTPServer.HTTPServer
是 SocketServer.TCPServer
的子类,它支持 shutdown
方法,但它缺失了在 HTTPServer
。
整个 BaseHTTPServer
模块的文档很少:(
解决方案
我应该首先说“我可能不会自己这样做,但我过去”。 serve_forever(来自SocketServer.py)方法如下所示:
def serve_forever(self):
"""Handle one request at a time until doomsday."""
while 1:
self.handle_request()
你可以用替换(子类中)
而>>而self.should_be_running
,并从另一个线程修改该值。类似的东西:
def stop_serving_forever(self):
"""Stop handling requests"""
self.should_be_running = 0
# Make a fake request to the server, to really force it to stop.
# Otherwise it will just stop on the next request.
# (Exercise for the reader.)
self.make_a_fake_request_to_myself()
编辑:我挖出了当时使用的实际代码:
class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
stopped = False
allow_reuse_address = True
def __init__(self, *args, **kw):
SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
self.register_function(lambda: 'OK', 'ping')
def serve_forever(self):
while not self.stopped:
self.handle_request()
def force_stop(self):
self.server_close()
self.stopped = True
self.create_dummy_request()
def create_dummy_request(self):
server = xmlrpclib.Server('http://%s:%s' % self.server_address)
server.ping()
其他提示
在我的python 2.6安装中,我可以在底层TCPServer上调用它 - 它仍然存在于 HTTPServer
中:
TCPServer.shutdown
>>> import BaseHTTPServer
>>> h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler)
>>> h.shutdown
<bound method HTTPServer.shutdown of <BaseHTTPServer.HTTPServer instance at 0x0100D800>>
>>>
我认为您可以使用 [serverName] .socket.close()
另一种方法,基于 http://docs.python.org/2 /library/basehttpserver.html#more-examples ,是:而不是serve_forever(),只要满足条件,就保持服务,服务器在每个请求之前和之后检查条件。例如:
import CGIHTTPServer
import BaseHTTPServer
KEEP_RUNNING = True
def keep_running():
return KEEP_RUNNING
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/cgi-bin"]
httpd = BaseHTTPServer.HTTPServer(("", 8000), Handler)
while keep_running():
httpd.handle_request()
事件循环在SIGTERM, Ctrl + C 或调用 shutdown()
时结束。
server_forever()
之后调用 server_close()
来关闭侦听套接字。
import http.server
class StoppableHTTPServer(http.server.HTTPServer):
def run(self):
try:
self.serve_forever()
except KeyboardInterrupt:
pass
finally:
# Clean-up server (close socket, etc.)
self.server_close()
简单服务器可以通过用户操作停止(SIGTERM, Ctrl + C ,...):
server = StoppableHTTPServer(("127.0.0.1", 8080),
http.server.BaseHTTPRequestHandler)
server.run()
服务器在线程中运行:
import threading
server = StoppableHTTPServer(("127.0.0.1", 8080),
http.server.BaseHTTPRequestHandler)
# Start processing requests
thread = threading.Thread(None, server.run)
thread.start()
# ... do things ...
# Shutdown server
server.shutdown()
thread.join()
在python 2.7中,调用shutdown()可以正常工作,但前提是你通过serve_forever服务,因为它使用async select和一个轮询循环。使用handle_request()运行你自己的循环具有讽刺意味的是排除了这个功能,因为它意味着一个愚蠢的阻塞调用。
来自SocketServer.py的BaseServer:
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__is_shut_down.clear()
try:
while not self.__shutdown_request:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if self in r:
self._handle_request_noblock()
finally:
self.__shutdown_request = False
self.__is_shut_down.set()
我的部分代码是从另一个线程执行阻塞关闭,使用事件等待完成:
class MockWebServerFixture(object):
def start_webserver(self):
"""
start the web server on a new thread
"""
self._webserver_died = threading.Event()
self._webserver_thread = threading.Thread(
target=self._run_webserver_thread)
self._webserver_thread.start()
def _run_webserver_thread(self):
self.webserver.serve_forever()
self._webserver_died.set()
def _kill_webserver(self):
if not self._webserver_thread:
return
self.webserver.shutdown()
# wait for thread to die for a bit, then give up raising an exception.
if not self._webserver_died.wait(5):
raise ValueError("couldn't kill webserver")
我成功使用此方法(Python 3)从Web应用程序本身(网页)停止服务器:
import http.server
import os
import re
class PatientHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
stop_server = False
base_directory = "/static/"
# A file to use as an "server stopped user information" page.
stop_command = "/control/stop.html"
def send_head(self):
self.path = os.path.normpath(self.path)
if self.path == PatientHTTPRequestHandler.stop_command and self.address_string() == "127.0.0.1":
# I wanted that only the local machine could stop the server.
PatientHTTPRequestHandler.stop_server = True
# Allow the stop page to be displayed.
return http.server.SimpleHTTPRequestHandler.send_head(self)
if self.path.startswith(PatientHTTPRequestHandler.base_directory):
return http.server.SimpleHTTPRequestHandler.send_head(self)
else:
return self.send_error(404, "Not allowed", "The path you requested is forbidden.")
if __name__ == "__main__":
httpd = http.server.HTTPServer(("127.0.0.1", 8080), PatientHTTPRequestHandler)
# A timeout is needed for server to check periodically for KeyboardInterrupt
httpd.timeout = 1
while not PatientHTTPRequestHandler.stop_server:
httpd.handle_request()
这样,通过基地址 http:// localhost:8080 / static /
提供的页面(例如 http:// localhost:8080 / static / styles / common.css
)将由默认处理程序提供,从服务器的计算机访问 http:// localhost:8080 / control / stop.html
将显示 stop.html
然后停止服务器,禁止任何其他选项。
我尝试了以上所有可能的解决方案,最终得到了“有时”的解决方案。问题 - 不知怎的,它并没有真正做到 - 所以我最终制作了一个对我来说一直都有效的肮脏解决方案:
如果以上都失败了,那么暴力破坏你的线程会使用类似的东西:
import subprocess
cmdkill = "kill $(ps aux|grep '<name of your thread> true'|grep -v 'grep'|awk '{print $2}') 2> /dev/null"
subprocess.Popen(cmdkill, stdout=subprocess.PIPE, shell=True)