Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a simplehttpserver in python from httprequest handler?

Tags:

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()
like image 538
user1429322 Avatar asked Jul 05 '16 06:07

user1429322


People also ask

How do I stop SimpleHTTPServer?

CTRL+C is pressed to stop the server. Run the following command to start the webserver at 8080 port.

How do I shut down HTTP server in Python?

Just use ^C (control+c) to shut down python server.

What is SimpleHTTPServer Python?

The SimpleHTTPServer module is a Python module that enables a developer to lay the foundation for developing a web server. However, as sysadmins, we can use the module to serve files from a directory. Usage. Python must be installed to use the SimpleHTTPServer module.


1 Answers

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()
like image 108
UltraInstinct Avatar answered Sep 28 '22 02:09

UltraInstinct