SimpleHTTPServer 的编程 API

当我们执行 python -m SimpleHTTPServer 9000 时会发生什么?

要回答这个问题,我们应该了解 SimpleHTTPServer( https://hg.python.org/cpython/file/2.7/Lib/SimpleHTTPServer.py) 和 BaseHTTPServer( https://hg.python.org/cpython/file 的结构。 /2.7/Lib/BaseHTTPServer.py)

首先,Python 使用 9000 作为参数调用 SimpleHTTPServer 模块。现在观察 SimpleHTTPServer 代码,

def test(HandlerClass = SimpleHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    test()

在请求处理程序和 ServerClass 之后调用测试函数。现在调用 BaseHTTPServer.test

def test(HandlerClass = BaseHTTPRequestHandler,
         ServerClass = HTTPServer, protocol="HTTP/1.0"):
"""Test the HTTP request handler class.

This runs an HTTP server on port 8000 (or the first command line
argument).

"""

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('', port)

HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

因此,这里将用户作为参数传递的端口号解析并绑定到主机地址。执行具有给定端口和协议的套接字编程的进一步基本步骤。最后启动套接字服务器。

这是从 SocketServer 类继承到其他类的基本概述:

    +------------+
    | BaseServer |
    +------------+
          |
          v
    +-----------+        +------------------+
    | TCPServer |------->| UnixStreamServer |
    +-----------+        +------------------+
          |
          v
    +-----------+        +--------------------+
    | UDPServer |------->| UnixDatagramServer |
    +-----------+        +--------------------+

链接 https://hg.python.org/cpython/file/2.7/Lib/BaseHTTPServer.pyhttps://hg.python.org/cpython/file/2.7/Lib/SocketServer.py 对于进一步查找非常有用信息。