使用BaseHTTPServer写一个简单的服务器,实现的功能很简单,只是把其中的html文件显示出来:

 1 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
 2 from os import sep, curdir
 3 import cgi
 4 
 5 
 6 PORT = 8080
 7     
 8 class myHandler(BaseHTTPRequestHandler):
 9             
10     def do_GET(self):
11 
12         if self.path == '/':
13             self.path = '\\test.html'
14             
15         try:
16             reply = False
17             if self.path.endswith('.html'):
18                 reply = True
19                 mimeType = 'text/html'
20                 
21             if self.path.endswith('.jpg'):
22                 reply = True
23                 mimeType = 'image.jpg'
24                 
25             if self.path.endswith('.js'):
26                 reply = True
27                 mimeType = 'application/javascript'
28                 
29             if self.path.endswith('.txt'):
30                 reply = True
31                 mimeType = 'text/txt'
32                 
33             
34             if(reply == True):
35                 fp = open(curdir + sep + self.path)
36                 self.send_response(200)
37                 self.send_header('content-type', mimeType)
38                 self.end_headers()
39                 self.wfile.write(fp.read())
40                 fp.close()
41             return
42         except IOError:
43             self.send_error(404, 'Not Found File %s' %self.path);
44         
45     def do_POST(self):
46         form = cgi.FieldStorage(
47                                 fp = self.rfile,
48                                 headers = self.headers,
49                                 environ = {
50                                            'REQUEST_METHOD':'POST',
51                                            'CONTENT_TYPE':self.headers.getheader('current-type')
52                                            }
53                                 )
54         
55         print form
56         
57         
58 
59         #self.wfile.write(form['name'])
60 
61     
62 try:
63     ser = HTTPServer(('', PORT), myHandler) 
64     print '\n\nStart HTTP Server at PORT:' , PORT
65     ser.serve_forever()
66 except KeyboardInterrupt:
67     print 'Shutting down the server!!'
68     ser.socket.close()

其中的do_GET方法是设置html文件,判断self.path的文件类型,定义mimetype,然后发送用open打开的文件数据,do_POST方法,就我目前的理解,相当于,GET就是获取到html文件,然后将html文件显示到页面上,而post的功能,可以将页面上的输入姓名,密码的文本利用python中的cgi模块传回,并且可以通过print form['key']值,显示key对应的值到终端。

其中的关窍还有待加深,看到文章的人不能轻信。

GET是向服务器索取数据的一种请求,POST是想服务器提交数据的一种请求,GET是获取信息,并不修改信息。

 

下面的方法是通过SimpleHTTPServer而不是BaseHTTPServer来写一个python的web服务器,相比较起来,SimpleHTTPServer俩的比较简单。

 1 import SimpleHTTPServer
 2 import SocketServer
 3 import cgi
 4 
 5 host = ''
 6 port = 8080
 7 
 8 
 9 class simpleHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
10     def do_POST(self):
11         try:
12             
13             form = cgi.FieldStorage(
14                                     fp = self.rfile,
15                                     headers = self.headers,
16                                     environ = {
17                                                'REQUEST_METHOD':'POST',
18                                                'CONTENT_TYPE':self.headers.getheader('current-type')
19                                                }    
20                                     )
21         
22 
23             print form
24     
25 
26         except IOError:
27             self.send_error(404, ' POST error');
28 
29  
30 conn = SocketServer.TCPServer((host, port), simpleHandler)
31 
32 
33 print 'start server at port:', port
34 
35 conn.serve_forever()

这上面并没有显示的说明html文件类型或者其他文件,但是SimpleHTTPServer它的do_GET()方法(这里不用重写,服务器自己调用)的请求映射到当前的文件夹,它会主动查找在当前目录或者子目录下的名字为index.html文件,如果没有这个文件,就调用list_directory()方法浏览目录,如果调用失败,返回404 error。

 

 

以上还有一个问题,假如html文件中有引用到script css文件,或者其他的webm等类型的video视频,用BaseHTTPServer只能显示出html页面,但是其中并不会调用js脚本和css文件(html代码中已经包含了

1     <head>
2         <title>HTML5 video</title>
3         <link type='text/css' rel='stylesheet' href='style.css'>
4         <script src='script.js' type='application/javascript'></script>
5     </head>

 

),webm的视频也显示不出来,页面报错找不到这个类型,但是SimpleHTTPServer都可以,是不是因为BaseHTTPServer比较基本,还需要在GET中加入parse的成分?

posted on 2013-03-25 13:40  二师兄89  阅读(932)  评论(0)    收藏  举报