如何本身實現一個最簡單web的服務器呢? 首先,你必須容許外部IP來訪問你的IP,並開啓一個端口不斷的去監聽他,python已經有模塊實現這樣的API供咱們監聽端口html
import BaseHTTPServer serverip=(' ',8080) server=BaseHTTPServer.HTTPServer(serverip,RequestHandler) server.server_forever()
其中RequestHandler表示須要處理的鏈接,咱們說通常最多見的鏈接時HTTP協議,咱們知道HTTP協議中經過請求的方法有兩種:GET和POST,這裏以GET爲例。python
def do_GET(self): self.send_response(200) self.send_header('content-type','html/txt')
在這裏你能夠添加想發送的頭的關鍵字和值。而後就是發送請求獲得的應答的內容了。 這裏是相關的請求說明web
self.wfile.write(content)
到這裏其實發送一個應答任務已經完成了,可是爲了保證傳輸的質量,因此要對輸入進行過濾。服務器
full_path=os.getcwd()+self.path if not os.path.exists(full_path): raise Exception("{0} is no found".format(self.path)) elif os.path.isfile(full_path): self.handler_file(full_path) else: raise Exception("unknow error is {0}".format(self.path)) except Exception as msg: handle_error(self,msg)
這些基本功能保證了請求的規範性,可是對於代碼的維護性仍是不夠,這裏能夠對每一種錯誤也轉換成類的方式,好比:code
class case_no_file(object): def test(self,handler): return os.path.exists(handler.full_path) def act(self,handler): raise Exception("{0} no found ".format(handler.full_path))
最後再來講下CGI吧,若是想在服務器裏添加新的內容該怎麼辦?直接修改源碼那會很麻煩,因此就用到CGI來實現。好比我想增長時間輸出的標籤該怎麼辦?先新建一個python文件:time.pyorm
from datetime import datetime print '''\ <html> <body> <p>Generated {0}</p> </body> </html>'''.format(datetime.now())
而後只要把這個的輸出發送給服務器就能夠了。server
import subprocess class case_cgi(object): def test(self,handler): return os.path.isfile(handler.full_path) and handler.full_path.endwith('.py') def act(self,handler): run_cgi(handler) def run_cgi(self,handler): data=subprocess.check_output(['python',handler.full_path]) handler.send_message(data)
OK,這個就是服務器了。雖然是練手,可是細節仍是有的。htm