How do I shutdown an HTTPServer from inside a request handler in Python?

↘锁芯ラ 提交于 2019-12-23 19:09:13

问题


How do I shutdown this server when I receive the StopIteration exception? sys.exit() does not work.

#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 2000

from itertools import islice
filename = 'data/all.txt'
file = open(filename, 'r')
lines_gen = islice(file, None)

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global lines_gen

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

        try:
            for i in range(10):
                next_line = lines_gen.next()
                self.wfile.write(next_line)
        except StopIteration:
            # return response and shutdown the server
            # ?????

        return

try:
    server = HTTPServer(('', PORT_NUMBER), MyHandler)
    print('Started httpserver on port ' , PORT_NUMBER)
    server.serve_forever()

except KeyboardInterrupt:
    print('^C received, shutting down the web server')
    server.socket.close()

回答1:


Just call shutdown() in a second thread.

# return response and shutdown the server
import threading
assassin = threading.Thread(target=server.shutdown)
assassin.daemon = True
assassin.start()


来源:https://stackoverflow.com/questions/19040055/how-do-i-shutdown-an-httpserver-from-inside-a-request-handler-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!