Python socketserver.ThreadingMixIn() Examples

The following are 5 code examples of socketserver.ThreadingMixIn(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socketserver , or try the search function .
Example #1
Source File: python_test_server.py    From dcos with Apache License 2.0 8 votes vote down vote up
def do_POST(self):  # noqa: ignore=N802
        """Mini service router handling POST requests"""
        if self.path == '/your_ip':
            try:
                self._handle_path_your_ip()
            except RequestProcessingException as e:
                logging.error("Request processing exception occured: "
                              "code: {}, reason: '{}', explanation: '{}'".format(
                                  e.code, e.reason, e.explanation))
                self.send_error(e.code, e.reason, e.explanation)
        elif self.path == '/signal_test_cache':
            self._handle_path_signal_test_cache(True)
        elif self.path == '/run_cmd':
            self._handle_path_run_cmd()
        else:
            self.send_error(404, 'Not found', 'Endpoint is not supported')


# We use a HTTPServer with the ThreadingMixIn in order to handle stalled HTTP requess. Without this, the behaviour
# is to handle requests serially. If a connection is severed, this can result in the server hanging for the TCP
# timeout before answering another requests...leading to failures. 
Example #2
Source File: conftest.py    From pytorch-lightning with Apache License 2.0 7 votes vote down vote up
def tmpdir_server(tmpdir):
    if sys.version_info >= (3, 7):
        Handler = partial(SimpleHTTPRequestHandler, directory=str(tmpdir))
        from http.server import ThreadingHTTPServer
    else:
        # unfortunately SimpleHTTPRequestHandler doesn't accept the directory arg in python3.6
        # so we have to hack it like this
        import os

        class Handler(SimpleHTTPRequestHandler):
            def translate_path(self, path):
                # get the path from cwd
                path = super().translate_path(path)
                # get the relative path
                relpath = os.path.relpath(path, os.getcwd())
                # return the full path from root_dir
                return os.path.join(str(tmpdir), relpath)

        # ThreadingHTTPServer was added in 3.7, so we need to define it ourselves
        from socketserver import ThreadingMixIn
        from http.server import HTTPServer

        class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
            daemon_threads = True

    with ThreadingHTTPServer(('localhost', 0), Handler) as server:
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        yield server.server_address
        server.shutdown() 
Example #3
Source File: ProxyTool.py    From ProxHTTPSProxyMII with MIT License 5 votes vote down vote up
def demo():
    PORT = 8000

    class ProxyServer(ThreadingMixIn, HTTPServer):
        """Handle requests in a separate thread."""
        pass

    class RequestHandler(ProxyRequestHandler):
        "Displaying HTTP request information"
        server_version = "DemoProxy/0.1"

        def do_METHOD(self):
            "Universal method for GET, POST, HEAD, PUT and DELETE"
            message = self.http_request_info()
            self.send_response(200)
            # 'Content-Length' is important for HTTP/1.1
            self.send_header('Content-Length', len(message))
            self.end_headers()
            self.wfile.write(message)

        do_GET = do_POST = do_HEAD = do_PUT = do_DELETE = do_OPTIONS = do_METHOD

    print('%s serving now, <Ctrl-C> to stop ...' % RequestHandler.server_version)
    print('Listen Addr  : localhost:%s' % PORT)
    print("-" * 10)
    server = ProxyServer(('', PORT), RequestHandler)
    server.serve_forever() 
Example #4
Source File: runserver.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def run(self, *args, **options):
        threading = options.get("use_threading", False)
        if threading:
            # This is a simple backport from Django's future
            # version to support threading.
            class ThreadedWSGIServer(ThreadingMixIn, WSGIServer):
                pass

            # Monkey patch basehttp.WSGIServer.
            setattr(basehttp, "WSGIServer", ThreadedWSGIServer)

        start_up()
        return super().run(*args, **options) 
Example #5
Source File: container_manager.py    From harpoon with MIT License 4 votes vote down vote up
def make_server(manager, address):
    class RequestHandler(BaseHTTPRequestHandler):
        def handle(self):
            try:
                super().handle()
            except KeyboardInterrupt:
                raise
            except Exception as error:
                self.send_response(500)
                self.send_header("Content-Type", "application/json")
                self.end_headers()

                if isinstance(error, DelfickError):
                    asdct = error.as_dict()
                else:
                    log.exception("Unexpected error")
                    asdct = {"message": str(error)}

                e = {"error": asdct, "error_code": error.__class__.__name__}
                self.wfile.write(json.dumps(e, default=lambda o: repr(o)).encode())

        def do_GET(self):
            if self.path == "/version":
                manager.version(self)
            elif self.path == "/shutdown":
                if manager.shutting_down:
                    self.send_response(204)
                    self.end_headers()
                else:
                    manager.shutdown(self)
            else:
                self.send_response(404)
                self.end_headers()
                self.wfile.write("Unknown path: {0}".format(self.path).encode())

        def do_POST(self):
            if self.path == "/stop_container":
                manager.stop_container(self)
            elif self.path == "/start_container":
                manager.start_container(self)
            elif self.path == "/unlock_container":
                manager.unlock_container(self)
            else:
                self.send_response(404)
                self.end_headers()
                self.wfile.write("Unknown path: {0}".format(self.path).encode())

        def log_message(self, format, *args):
            log.info("%s - %s", self.address_string(), format % args)

    class Server(socketserver.ThreadingMixIn, HTTPServer):
        pass

    return Server(address, RequestHandler)