Python的SimpleHTTPServer

来源:互联网 发布:人工智能在智慧物流 编辑:程序博客网 时间:2024/04/29 21:33

今天花了一点时间来看看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)