[Python] How do you make asynchronous BaseHTTPREQUESTHandler python server work?

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    This is what I have. It says OSError: [Errno 98] Address already in use:


    import threading
    import _thread

    def GET(self):

    print(self.path)


    path = self.path[1:]
    print(f"path [{path}]")

    message = "";

    self.send_response(200)
    self.send_header('Content-type','text/html')
    self.end_headers()

    f = open(path)
    message = f.read()
    self.wfile.write(bytes(message, "utf8"))

    def SERVE():
    with HTTPServer(('0.0.0.0', 8000), handler) as server:
    server.serve_forever()

    class handler(BaseHTTPRequestHandler):

    def do_GET(self):

    t1 = threading.Thread(target=GET,args=(self))
    t2 = threading.Thread(target=SERVE)
    t1.start()
    t2.start()


    import socketserver
    import socket

    with HTTPServer(('0.0.0.0', 8000), handler) as server:

    server.serve_forever()


    I'm trying to make it work in run parallel code using threads since they where easier to use than multiprocessing.

    I can't seem to get the SO_REUSEADDR to work with the socket in the code. They always say to do this but I don't know how to set this setting to the socket in my code (or behind the BaseHTTPRequestHandler a.k.a server.

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    Seems like they just threw this one line of code without the context on how to make it work.

    It also seems to be one for TCPServer but I'm not sure about the rest of the code:

    if self.allow_reuse_address and hasattr(socket, "SO_REUSEADDR"):
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    if self.allow_reuse_port and hasattr(socket, "SO_REUSEPORT"):
    self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    self.socket.bind(self.server_address)
    self.server_address = self.socket.getsockname()

    Continue reading...

Compartilhe esta Página