對于web開發(fā),Pyhon 3 提供了HTTP Server模塊,這個模塊提供了創(chuàng)建和監(jiān)聽Http socket,并對http 請求進行調(diào)度的一系列類。
想創(chuàng)建一個本地的http服務(wù)器時,又不想安裝IIS等靜態(tài)服務(wù)器,那么python的httpserver是一個很好的選擇。
那么如何創(chuàng)建一個http服務(wù)器呢?
1.首先,導入對http server模塊進行導入:
#server.py
import http.server
from http.server import HTTPServer
2.監(jiān)聽端口,運行服務(wù)
#server.py
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = HTTPServer(("", PORT), Handler)
httpd.serve_forever()
3.同級別目錄創(chuàng)建一個 index.html文件,內(nèi)容如下
python http server !
4.命令行輸入:python server.py
5.打開瀏覽器輸入:http://localhost:8000/? 顯示:python http server !
下面的代碼同樣可以實現(xiàn)上面的httpsever的功能
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
區(qū)別是處理監(jiān)聽和相應(yīng)http響應(yīng)的類不同,此處使用的是socketserver.TCPServer類。上面使用的?HTTPServer
HTTPServe 類是socketserver.TCPServer的子類
參考:
https://docs.python.org/3/library/http.server.html#module-http.server