参考: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
中设置这些回调?!
答案 0 :(得分:4)
使用以下内容配置http服务器会很棒 回调:
- 启动服务器之前
- 启动服务器后
- 停止服务器之前
停止服务器后
请记住,操作系统将在套接字开始侦听时开始接受和排队TCP连接,这在BaseHTTPServer
的构造函数中完成,因此如果您想在启动服务器之前执行冗长的任务,那么在OS开始接受连接之前,最好先做它们。
有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,server
变量将不存在。
答案 1 :(得分:3)
您必须继承HTTPServer
并使用您的班级HTTPServer
from __future__ import print_function
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
class MyHTTPServer(HTTPServer):
def __init__(self, *args, **kwargs):
self.on_before_serve = kwargs.pop('on_before_serve', None)
HTTPServer.__init__(self, *args, **kwargs)
def serve_forever(self, poll_interval=0.5):
if self.on_before_serve:
self.on_before_serve(self)
HTTPServer.serve_forever(self, poll_interval)
# http request handler
class HttpHandler(BaseHTTPRequestHandler):
def do_POST(self):
print("I have just received a HTTP request through POST")
try:
server = MyHTTPServer(('0.0.0.0', 8080), HttpHandler,
on_before_serve = lambda server: print('Server will start to serve in the moment...'))
# wait forever for incoming http requests!
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()