標籤:自訂 art server start 輸出 標準 請求 latest http
使用原生的python開發的web伺服器,入門級!
#!/usr/bin/python# -*- coding: UTF-8 -*-import os #Python的標準庫中的os模組包含普遍的作業系統功能 import re #引入Regex對象 import urllib #用於對URL進行編解碼 from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler #匯入HTTP處理相關的模組 #自訂處理常式,用於處理HTTP請求 class TestHTTPHandler(BaseHTTPRequestHandler): #處理GET請求 def do_GET(self): #擷取URL print ‘URL=‘,self.path #頁面輸出模板字串 templateStr = ‘‘‘ <html> <head> <title>QR Link Generator</title> </head> <body> hello Python! </body> </html> ‘‘‘ self.protocal_version = ‘HTTP/1.1‘ #設定協議版本 self.send_response(200) #設定響應狀態代碼 self.send_header("Welcome", "Contect") #設定回應標頭 self.end_headers() self.wfile.write(templateStr) #輸出響應內容 #啟動服務函數 def start_server(port): http_server = HTTPServer((‘‘, int(port)), TestHTTPHandler) http_server.serve_forever() #設定一直監聽並接收請求 #os.chdir(‘static‘) #改變工作目錄到 static 目錄 start_server(8000) #啟動服務,監聽8000連接埠
Python httpServer伺服器(初級)