How to implement Timeout in BaseHTTPServer.BaseHTTPRequestHandler Python

前端 未结 7 1260
走了就别回头了
走了就别回头了 2021-01-19 01:46

In my python script, I am trying to run a web server:

server = BaseHTTPServer.HTTPServer((\'127.0.0.1\',8080), RequestHandler)

I have a req

7条回答
  •  被撕碎了的回忆
    2021-01-19 02:08

    As pointed out by Tey' in TinBane's answer, timeout attribute will not work with serve_forever() method, as stated in the doc:

    The workaround is to use a custom loop for handling the request as pointed out by user3483992

    while True: server.handle_request()
    

    handle_request() will then trigger the method handle_timeout() at the end of the given timeout as expected:

    ...except the handle_timeout method is doing nothing:

    A solution is then to provide another implementation for this method, such as (credit here):

    server.handle_timeout = lambda: (_ for _ in ()).throw(TimeoutError())
    

    In short:

    try:
         server = HTTPServer(('', PORT_NUMBER), `yourAwesomeRequestHandler`)
         server.timeout = 10
         server.handle_timeout = lambda: (_ for _ in ()).throw(TimeoutError())
         while True: server.handle_request()
    except TimeoutError:
        // TODO
    

提交回复
热议问题