Python3搭建http伺服器的實現程式碼
阿新 • • 發佈:2020-02-11
在本機搭建Web伺服器其實也有更簡單的方法,可以利用iis功能。可以自行搜尋本機iis搭建Web伺服器。不用寫程式碼,Windows自帶的web伺服器功能。
Python2提供了BaseHTTPServer模組,不過在Py3把它合併到了http.server中。
老教材用BaseHTTPServer你可以直接用http.server代替即可。
這裡利用http.server搭建最簡單的web伺服器:
from http.server import HTTPServer,BaseHTTPRequestHandler class Request(BaseHTTPRequestHandler): def do_GET(self): print(self.path) self.send_response(200) # 標識傳遞資料型別 self.send_header('Content-type','text/html') self.end_headers() self.wfile.write('這裡用來傳資料') # 下面的形式可以用來傳html檔案 # with open('D:\\Python網路程式設計基礎\\Python程式碼\\http.html','rb') as t: # print('輸出了') # self.wfile.write(t.read()) def run(): host='localhost' port=80 server=HTTPServer((host,port),Request) server.serve_forever() if __name__=='__main__': # print(Request.path) run()
然後可以用瀏覽器,訪問localhost,預設的是80埠。
一般80是http,443是https,這裡你也可以用別的埠。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。