from: http://www.lifeba.org/arch/python_http_simplehttpserver_basehttpserver_cgihttpserver.html
Python的“Web服务器模块”有如下三种
一、SimpleHTTPServer:包含执行GET和HEAD请求的SimpleHTTPRequestHandler类。
通过下面命令我们创建了HTTP服务,默认使用8000端口号监听。通过:http://localhost:8000/ 就可以访问,如果文件夹下有index.html,那么这个文件就会成为一个默认页,如果没有这个文件,那么,目录列表就会显示出来。
python -m SimpleHTTPServer
python -m SimpleHTTPServer 8080 #指定端口号
二、BaseHTTPServer,提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler。
主要代码(完整代码参考附件下载):
启动一个8000监听的httpserver,由MyRequestHandler处理请求。
1
2
3
|
server
=
HTTPServer(('',
8000
), MyRequestHandler)
print
'started httpserver...'
server.serve_forever()
|
MyRequestHandler类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
class
MyRequestHandler(BaseHTTPRequestHandler):
def
do_GET(
self
):
self
.process(
2
)
def
do_POST(
self
):
self
.process(
1
)
def
process(
self
,
type
):
content
=
""
if
type
=
=
1
:
#post方法,接收post参数
datas
=
self
.rfile.read(
int
(
self
.headers[
'content-length'
]))
datas
=
urllib.unquote(datas).decode(
"utf-8"
,
'ignore'
)
#指定编码方式
datas
=
transDicts(datas)
#将参数转换为字典
if
datas.has_key(
'data'
):
content
=
"data:"
+
datas[
'data'
]
+
"\r\n"
if
'?'
in
self
.path:
query
=
urllib.splitquery(
self
.path)
action
=
query[
0
]
if
query[
1
]:
#接收get参数
queryParams
=
{}
for
qp
in
query[
1
].split(
'&'
):
kv
=
qp.split(
'='
)
queryParams[kv[
0
]]
=
urllib.unquote(kv[
1
]).decode(
"utf-8"
,
'ignore'
)
content
+
=
kv[
0
]
+
':'
+
queryParams[kv[
0
]]
+
"\r\n"
#指定返回编码
enc
=
"UTF-8"
content
=
content.encode(enc)
f
=
io.BytesIO()
f.write(content)
f.seek(
0
)
self
.send_response(
200
)
self
.send_header(
"Content-type"
,
"text/html; charset=%s"
%
enc)
self
.send_header(
"Content-Length"
,
str
(
len
(content)))
self
.end_headers()
shutil.copyfileobj(f,
self
.wfile)
|
说明:
1、get测试:http://steven-pc:8000/?test=data
2、通过curl来测试post数据:
curl -d "data=postdata" http://steven-pc:8000?test=post
data:postdata
test:post
3、支持中文:必须在头部加:#encoding=utf-8
三、CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类。
参考 CGI介绍及使用Python来开发CGI应用示例
四、资源下载
BaseHTTPServer DEMO下载: lifeba.org_HTTPServerDemo
================================
a simple multi-process server demo
import BaseHTTPServer
import urlparse
import time
from SocketServer import ThreadingMixIn
import threading
class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
print 'post message'
parsed_path = urlparse.urlparse(self.path)
length = self.headers.getheader('content-length');
nbytes = int(length)
data = self.rfile.read(nbytes)
cur_thread = threading.currentThread()
print 'Thread:%s\tdata:%s' % (cur_thread.getName(), data)
for i in range(10) :
print '%s:waiting...' % cur_thread.getName()
time.sleep(1)
message_parts = [ 'just a test']
message = '\r\n'.join(message_parts)
self.send_response(200)
self.end_headers()
self.wfile.write(message)
class ThreadingHttpServer( ThreadingMixIn, BaseHTTPServer.HTTPServer ):
pass
if __name__ == '__main__':
#server = BaseHTTPServer.HTTPServer(('0.0.0.0',18460), WebRequestHandler)
server = ThreadingHttpServer(('0.0.0.0',18460), WebRequestHandler)
ip, port = server.server_address
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.setDaemon(True)
server_thread.start()
print "Server loop running in thread:", server_thread.getName()
while True:
pass