简体   繁体   中英

How to stop a simplehttpserver in python from httprequest handler?

I am new to python and wrote a simple httpserver in python. 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(..) . 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.

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. A HTTPServer that was started with server_forerver can be shut down with its... shutdown() method. Unfortunately, even if it is not documented, you cannot call shutdown from the thread that runs the server loop because it causes a deadlock. So you could write this in your do_GET handler method:

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:

def shut_down(self):
    self._server.shutdown()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM