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

标签 python http callback basehttpserver

引用: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()

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

假设我们有以下函数:

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 block 中,因为如果您点击 server 变量将不存在构建过程中的 CTRL-C。

关于Python BaseHTTPServer.HTTPServer - 启动和停止事件的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16730771/

相关文章:

javascript - 使用 AcornJS 中的同步回调处理程序远离全局状态

java - java中的回调是什么?

python - 如何删除输出末尾的空格

java - 基于 Spring 的 Web 应用程序中的分块 HTTP 响应

Python:确定损益

对完整站点的 android http 请求(避免移动版本)

node.js - 将 .htacees 指向使用 SSL 配置的 Node 服务器

iphone - flickr 回调 URL 无效

python - 如何读取pandas中的第一列和最后一列?

python - 有没有一种更快的方法使用 numpy 中的矢量化操作从大型二维数组中恢复图像