1. 程式人生 > >Python的SimpleHTTPServer

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)

相關推薦

no