Python BaseHTTPServer.HTTPServer – 启动和停止事件的回调

参考:
http://docs.python.org/2/library/basehttpserver.html

我有以下代码片段,它使用Python BaseHTTPServer来运行基本的HTTP服务器.

from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler

# http request handler
class HttpHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        print "I have just received a HTTP request through POST"

try:
    server = HTTPServer((<ip>, <port>), HttpHandler)

    # wait forever for incoming http requests!
    server.serve_forever()

except KeyboardInterrupt:
    server.socket.close()

我正在寻找的是一种在使用server.serve_forever()/ server.socket.close()方法启动/停止http服务器时获得回调的方法.

假设我们有以下功能:

def http_server_start_callback():
    print "http server has just been started" 

def http_server_stop_callback():
    print "http server has just been stopped" 

我希望http_server_start_callback函数在我启动服务器之后立即被调用,即server.serve_forever(),我希望在我停止服务器之后立即调用http_server_stop_callback函数,即server.socket.close()

使用以下回调配置http服务器会很棒:

>在启动服务器之前
>启动服务器后
>在停止服务器之前
>停止服务器后

有没有办法在Python BaseHTTPServer.HTTPServer中设置这些回调?!

最佳答案

It would be excellent to configure the http server with the following
callbacks:

  • before starting the server
  • after starting the server
  • before stopping the server
  • after stopping the server

请记住,操作系统将在套接字开始侦听时开始接受和排队TCP连接,这是在BaseHTTPServer的构造函数中完成的,所以如果要在启动服务器之前执行冗长的任务,最好在执行之前执行这些操作.操作系统开始接受连接.

有一个server_activate()方法调用socket.listen(),所以最好覆盖它.

类似地,操作系统将继续接受连接,直到调用socket.close()为止,所以如果你想能够定义一个能够防止自身被关闭的“预停止”处理程序,那么它可能更好.使用server_close()方法,而不是直接调用socket.close().

我已经汇总了一个简单的例子,在请求处理程序上使用类方法来处理这四个新事件,尽管你可以将它们移动到其他地方……

from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler

# Subclass HTTPServer with some additional callbacks
class CallbackHTTPServer(HTTPServer):

    def server_activate(self):
        self.RequestHandlerClass.pre_start()
        HTTPServer.server_activate(self)
        self.RequestHandlerClass.post_start()

    def server_close(self):
        self.RequestHandlerClass.pre_stop()
        HTTPServer.server_close(self)
        self.RequestHandlerClass.post_stop()


# HTTP request handler
class HttpHandler(BaseHTTPRequestHandler):

    @classmethod
    def pre_start(cls):
        print 'Before calling socket.listen()'

    @classmethod
    def post_start(cls):
        print 'After calling socket.listen()'

    @classmethod
    def pre_stop(cls):
        print 'Before calling socket.close()'

    @classmethod
    def post_stop(cls):
        print 'After calling socket.close()'

    def do_POST(self):
        print "I have just received an HTTP POST request"


def main():

    # Create server
    try:
        print "Creating server"
        server = CallbackHTTPServer(('', 8000), HttpHandler)
    except KeyboardInterrupt:
        print "Server creation aborted"
        return

    # Start serving
    try:
        print "Calling serve_forever()"
        server.serve_forever()
    except KeyboardInterrupt:
        print "Calling server.server_close()"
        server.server_close()


if __name__ == '__main__':
    main()

请注意,我还将对构造函数的调用移动到它自己的try … except块中,因为如果在构造期间按CTRL-C,则服务器变量将不存在.

    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞