quo*_*tor 10
您应该查看SimpleHttpServer(py3:http.server)模块.
根据您要执行的操作,您可以使用它,也可以查看模块的源(py2,py3)以获取创意.
如果你想获得更多低级别,SimpleHttpServer扩展BaseHttpServer(源代码)使其正常工作.
如果你想获得甚至更低水平,看看SocketServer的(来源:PY2,PY3).
人们经常会像python -m SimpleHttpServer
(或python3 -m http.server
)那样运行python,如果他们只想共享一个目录:它是一个功能齐全且简单的服务器.
为此,可以使用套接字编程。以下代码段创建了一个tcp套接字,并在端口9000上侦听http请求:
from socket import *
def createServer():
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.bind(('localhost',9000))
serversocket.listen(5)
while(1):
(clientsocket, address) = serversocket.accept()
clientsocket.send("HTTP/1.1 200 OK\n"
+"Content-Type: text/html\n"
+"\n" # Important!
+"<html><body>Hello World</body></html>\n")
clientsocket.shutdown(SHUT_WR)
clientsocket.close()
serversocket.close()
createServer()
Run Code Online (Sandbox Code Playgroud)
启动服务器,$ python server.py
。http://localhost:9000/
在您的网络浏览器(充当客户端)中打开。然后,在浏览器窗口中,您可以看到文本“ Hello World”(http响应)。
编辑**先前的代码仅在chrome上进行了测试,正如你们对其他浏览器的建议,该代码被修改为:
shutdown()
需要称为socket.shutdown vs socket.close然后,在chrome,firefox(http:// localhost:9000 /)和终端中的简单curl(curl http:// localhost:9000)上对代码进行了测试。