[英]How to stop a simplehttpserver in python from httprequest handler?
I am new to python and wrote a simple httpserver in python. 我是python的新手,在python中编写了一个简单的httpserver。 I am trying to shut down the server from the request to the server.
我试图关闭服务器从请求到服务器。 How can I achieve this functionality of calling a function of the server from the handler?
如何从处理程序中实现调用服务器功能的这一功能?
class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/shutdown':
pass # I want to call MainServer.shutdown from here
class MainServer()
def __init__(self, port = 8123):
self._server = HTTPServer(('0.0.0.0', port), MyHandler)
self._thread = threading.Thread(target = self._server.serve_forever)
self._thread.deamon = True
def start(self):
self._thread.start()
def shut_down(self):
self._thread.close()
In short, do not use server.serve_forver(..)
. 简而言之,不要使用
server.serve_forver(..)
。 The request handler has a self.server
attribute that you can use to communicate with the main server instance to set some sort of flag that tell the server when to stop. 请求处理程序具有
self.server
属性,您可以使用该属性与主服务器实例进行通信,以设置某种标志,告诉服务器何时停止。
import threading
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/shutdown':
self.server.running = False
class MainServer:
def __init__(self, port = 8123):
self._server = HTTPServer(('0.0.0.0', port), MyHandler)
self._thread = threading.Thread(target=self.run)
self._thread.deamon = True
def run(self):
self._server.running = True
while self._server.running:
self._server.handle_request()
def start(self):
self._thread.start()
def shut_down(self):
self._thread.close()
m = MainServer()
m.start()
The server is normally accessible from the handler through the server
attribute. 通常可以通过
server
属性从处理程序访问server
。 A HTTPServer that was started with server_forerver
can be shut down with its... shutdown()
method. 可以使用其...
shutdown()
方法关闭使用server_forerver
启动的HTTPServer。 Unfortunately, even if it is not documented, you cannot call shutdown from the thread that runs the server loop because it causes a deadlock. 不幸的是,即使没有记录,也无法从运行服务器循环的线程调用shutdown,因为它会导致死锁。 So you could write this in your
do_GET
handler method: 所以你可以在你的
do_GET
处理程序方法中写这个:
def do_GET(self):
# send something to requester...
if self.path == '/shutdown':
t = threading.Thread(target = self.server.shutdown)
t.daemon = True
t.start()
This will cleanly let the thread to terminate, and you should also use it as you server shut_down
method, because Python threads cannot be closed abruptly: 这将干净地让线程终止,你也应该在服务器的
shut_down
方法中使用它,因为Python线程不能突然关闭:
def shut_down(self):
self._server.shutdown()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.