Python的SimpleHTTPServer

今天花了一點時間來看看SimpleHTTPServer。
這是Python的一個模塊。

看這個的原因是想架一個簡單簡單簡單簡單的Http Server,實現這樣的功能:
用戶點擊一個按鈕,創建出一個IE(Firefox)界面,可以瀏覽Flash,
也可以點擊Flash中的按鈕或其他什麼什麼的,
然後通過Javascript傳到後臺,後臺我用Python來做處理。

本來這個功能是想用Karrigell來實現,但是有簡單的方法,就簡單一點。
我在Python2.5的Module Docs中看到SimpleHTTPServer的版本是0.6,
對應文件是c:/python25/lib/simplehttpserver.py。

介紹如下:(原文爲英文,這裏譯成中文)

Simple HTTP Server. 簡單的HTTP服務器。(譯註:如名所示)

This module builds on BaseHTTPServer by implementing the standard GET and HEAD requests in a fairly straightforward manner.
此模塊基於BaseHTTPServer,利用輕快明瞭的方式實現了標準的GET和HEAD請求。

我看到了其中的一個類:class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler),
介紹如下:(原文爲英文,翻譯爲中文)

Simple HTTP request handler with GET and HEAD commands.
簡單的HTTP請求處理方法,使用GET和HEAD命令。

This serves files from the current directory and any of its subdirectories.
The MIME type for files is determined by calling the .guess_type() method.
服務器上當前目錄下及子目錄下的文件。調用.guess_type()方法來判斷文件的MIME類型。

The GET and HEAD requests are identical except that the HEAD request omits the actual contents of the file.
GET和HEAD請求是同樣對待,除非HEAD請求忽略文件的真實內容。

我們來試一下:
01、創建一個HTML頁面,源碼如下:

Hello World!

保存爲:index.html

02、創建一個Python程序,源碼如下:

import SimpleHTTPServer
SimpleHTTPServer.test()

保存爲:test.py

03、在命令提示符下輸入:python test.py,回車,
可以看到:Serving HTTP on 0.0.0.0 port 8000 ...
打開IE,輸入:http://127.0.0.1:8000/ 看到了index.html頁面。

此時在命令提示符下可以看到:otherrrr - - [10/Jan/2008 16:23:58] "GET / HTTP/1.1" 200 -

04、最後提醒一句:使用Ctrl+Break關閉。 (本文所涉及環境:Windows2003/Python2.5)

發佈了15 篇原創文章 · 獲贊 0 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章