python SimpleHTTPServer源碼學習

來源:互聯網
上載者:User

標籤:serve   object   cep   lam   避免   set   for   AC   index   

SimpleHTTPServer.SimpleHTTPRequestHandler繼承了BaseHTTPServer.BaseHTTPRequestHandler。

源碼中主要實現了BaseHTTPServer.BaseHTTPRequestHandler處理時需要調用的do_Head()和do_GET()函數。這類函數主要是在BaseHTTPRequestHandler在接受請求並判斷要求標頭中的command之後調用的。

 def handle_one_request(self):            ... ...            mname = ‘do_‘ + self.command            if not hasattr(self, mname):                self.send_error(501, "Unsupported method (%r)" % self.command)                return            method = getattr(self, mname)            method()            ... ...

 因此,在我們使用SimpleHTTPServer 對web請求處理時基本都需要調用這個method(),當然,其他異常情況除外。

SimpleHTTPServer.SimpleHTTPRequestHandler預設的處理是,如果在執行該指令碼的目前的目錄含有 index.html或index.htm時,將把這個檔案的html內容作為首頁,如果不存在,則在介面顯示目前的目錄下的檔案夾內容,並內部將其設定html頁面展現方式。

    def list_directory(self, path):        """Helper to produce a directory listing (absent index.html).        Return value is either a file object, or None (indicating an        error).  In either case, the headers are sent, making the        interface the same as for send_head().        """        try:            list = os.listdir(path)        except os.error:            self.send_error(404, "No permission to list directory")            return None        list.sort(key=lambda a: a.lower())        f = StringIO()        displaypath = cgi.escape(urllib.unquote(self.path))        f.write(‘<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">‘)        f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)        f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)        f.write("<hr>\n<ul>\n")        for name in list:            fullname = os.path.join(path, name)            displayname = linkname = name            # Append / for directories or @ for symbolic links            if os.path.isdir(fullname):                displayname = name + "/"                linkname = name + "/"            if os.path.islink(fullname):                displayname = name + "@"                # Note: a link to a directory displays with @ and links with /            f.write(‘<li><a href="%s">%s</a>\n‘                    % (urllib.quote(linkname), cgi.escape(displayname)))        f.write("</ul>\n<hr>\n</body>\n</html>\n")        length = f.tell()        f.seek(0)        self.send_response(200)        encoding = sys.getfilesystemencoding()        self.send_header("Content-type", "text/html; charset=%s" % encoding)        self.send_header("Content-Length", str(length))        self.end_headers()        return f
SimpleHTTPRequestHandler中list_directory()

其實對於socket的請求整理是在SocketServer.TCPServer中處理的,對web要求標頭的處理是在BaseHTTPServer.BaseHTTPRequestHandler中處理的,其對頭的類型,版本等作了處理。而對於請求的回應則在子類SimpleHTTPServer.SimpleHTTPRequestHandler中處理。

那麼,SimpleHTTPServer.SimpleHTTPRequestHandler是如何作出上述說明的請求的呢?

首先,Simple通過send_head()函數內部預先分析了請求的url路徑,然後提取路徑與目前的目錄路徑組合得到請求的絕對路徑地址,如果在該路徑下存在index.html或index.htm檔案則將這個檔案內容開啟並設定回饋頭的內容,寫入檔案內容的長度和內容的類型,如果沒有這個檔案,則將擷取目前的目錄下的內容,建立一個檔案快取寫入一個html格式的內容,其中寫明目前的目錄所具有的內容並設定超連結,使得使用者點擊時伺服器能正確的回饋對應內容。

我們發現send_head()其實發送的要求標頭是根據請求內容進行設定的,也就是說在send_head()中,Simple已經把請求data準備好了,所以在send_head()之後只需要調用self.copyfile(f, self.wfile)將檔案對象或快取檔案對象中的內容寫入請求流對象中即可。

至於其他函數,都是為這些作準備的。

*值得注意的是,在讀取本地檔案回饋給用戶端時要注意檔案需要以rb的方式,即二進位方式去讀,這樣就避免文字資料流中換行了,也能正確的就算出流的長度(長度是作為回饋頭的一部分反饋出去的)。

python SimpleHTTPServer源碼學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.