python下的web服务器模块

python下的web服务模块有三种:

  BaseHTTPServer: 提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler

  SimpleHTTPServer: 包含执行GET和HEAD请求的SimpleHTTPRequestHandler类

  CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类。

下面是CGIHTTPServer类示例:

 1 root@u254:~/cp# tree
 2 .
 3 |-- cgi-bin
 4 |   |-- get_info.py
 5 |   |-- get_info.pyc
 6 |   `-- hick.py
 7 `-- http.py
 8 
 9 http.py
10 #!/usr/bin/python
11 #encoding=utf-8
12 #supported by python2.7
13 
14 import sys 
15 from CGIHTTPServer import CGIHTTPRequestHandler
16 from BaseHTTPServer import HTTPServer
17 server_addr = ('192.168.2.18', 20014)
18 httpd = HTTPServer(server_addr, CGIHTTPRequestHandler)
19 httpd.serve_forever()
20 
21 hick.py
22 #!/usr/bin/python
23 #encoding=utf-8
24 #supported python2.7
25 
26 import cgi
27 import sys
28 form = cgi.FieldStorage()
29 name = form["access"].value   #获取get传递的参数 
30 
31 print "HTTP/1.0 200 OK"
32 print "Content-Type:text/html"
33 print ""
34 print ""
35 print "name %s"% name  
36 print ""

执行效果图如下:  

SimpleHTTPServer示例:

  1 root@u254:~/cp# tree 
  2 .
  3 |-- get_info.py
  4 |-- get_info.pyc
  5 `-- http2.py
  6 
  7 get_info.py如下:
  8 #!/usr/bin/python
  9 #encoding=utf-8
 10 #supported python2.7
 11 
 12 import commands
 13 import json
 14 
 15 def GetInfo(id):
 16         cmd = "radosgw-admin -c /etc/ceph/ceph.conf bucket stats  --uid="+ str(id) +" --categories={}"
 17         #cmd = "radosgw-admin bucket stats  --uid=37 --categories={} --access=radosgw-admin  --access-key=37 --secret=IXJcIub8Zprn7Vu+Tm3VId0LdrnMCfgpZ6sSb9zc"
 18         dict_t = {}
 19         content = commands.getoutput(cmd)
 20         #print content
 21         if content.find(")") != -1: 
 22                 en_json = json.loads(content.split(')')[1])
 23         else:
 24                 en_json = json.loads(content)
 25         for element in en_json:
 26                 if "bucket" in element.keys() and "usage" in element.keys():
 27                         #print element["bucket"]
 28                         if "rgw.main" in element["usage"].keys() and "size_kb_actual" in element["usage"]["rgw.main"].keys():
 29                                 #print element["usage"]["rgw.main"]["size_kb_actual"]
 30                                 dict_t.setdefault(element["bucket"], element["usage"]["rgw.main"]["size_kb_actual"])
 31                         else:
 32                                 dict_t.setdefault(element["bucket"], 0)
 33         #print json.dumps(dict_t) 
 34         return json.dumps(dict_t) 
 35 
 36 
 37 if __name__ == "__main__":
 38     GetInfo(37)
 39 
 40 http2.py如下:
 41 #!/usr/bin/pyton
 42 #encoding=utf-8
 43 #supported by python2.7
 44 
 45 
 46 #encoding=utf-8
 47 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
 48 import io,shutil
 49 import urllib,time
 50 import sys 
 51 sys.path.append(r'./')
 52 import getopt,string
 53 import get_info
 54 
 55 class MyRequestHandler(BaseHTTPRequestHandler):
 56     def do_GET(self):
 57         self.process(2)
 58     def do_POST(self):
 59         self.process(1)
 60     
 61     def process(self,type):
 62         content ="" 
 63         if type==1:
 64             datas = self.rfile.read(int(self.headers['content-length']))
 65             datas = urllib.unquote(datas).decode("utf-8", 'ignore')
 66             datas = transDicts(datas)
 67             if datas.has_key('data'):
 68                 content = "data:"+datas['data']+"
"
 69     
 70         if '?' in self.path:
 71             query = urllib.splitquery(self.path)
 72             action = query[0]
 73             if query[1]:
 74                 queryParams = {}
 75                 for qp in query[1].split('&'):
 76                     kv = qp.split('=')
 77                     print kv[1]
 78                     kv[1] = get_info.GetInfo(kv[1])
 79                     queryParams[kv[0]] = urllib.unquote(kv[1]).decode("utf-8", 'ignore')
 80                     #content+= kv[0]+':'+queryParams[kv[0]]+"
"
 81                     content+= queryParams[kv[0]]+"
"
 82 
 83             enc="UTF-8"
 84             content = content.encode(enc)
 85             f = io.BytesIO()
 86             f.write(content)
 87             f.seek(0)
 88             self.send_response(200)
 89             self.send_header("Content-type", "text/html; charset=%s" % enc)
 90             self.send_header("Content-Length", str(len(content)))
 91             self.end_headers()
 92             shutil.copyfileobj(f,self.wfile)
 93 def transDicts(params):
 94     dicts={}
 95     if len(params)==0:
 96         return
 97     params = params.split('&')
 98     for param in params:
 99         dicts[param.split('=')[0]]=param.split('=')[1]
100     return dicts
101 
102 if __name__=='__main__':
103    try:
104         server = HTTPServer(('203.156.196.254', 20014), MyRequestHandler)
105         print 'started httpserver...'
106         server.serve_forever()
107    except KeyboardInterrupt:
108         server.socket.close()
109    pass

效果如下:

原文地址:https://www.cnblogs.com/chris-cp/p/4586871.html