博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python下的web服务器模块
阅读量:5797 次
发布时间:2019-06-18

本文共 4853 字,大约阅读时间需要 16 分钟。

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.py10 #!/usr/bin/python11 #encoding=utf-812 #supported by python2.713 14 import sys 15 from CGIHTTPServer import CGIHTTPRequestHandler16 from BaseHTTPServer import HTTPServer17 server_addr = ('192.168.2.18', 20014)18 httpd = HTTPServer(server_addr, CGIHTTPRequestHandler)19 httpd.serve_forever()20 21 hick.py22 #!/usr/bin/python23 #encoding=utf-824 #supported python2.725 26 import cgi27 import sys28 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']+"\r\n" 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]]+"\r\n" 81                     content+= queryParams[kv[0]]+"\r\n" 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 dicts101 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

效果如下:

 

转载地址:http://kpifx.baihongyu.com/

你可能感兴趣的文章
Squid 反向代理服务器配置
查看>>
情深意伤
查看>>
Java I/O操作
查看>>
Tomcat性能调优
查看>>
项目管理心得
查看>>
Android自学--一篇文章基本掌握所有的常用View组件
查看>>
排序算法总结(一)插入排序【Insertion Sort】
查看>>
python中if __name__ == '__main__': 的解析
查看>>
Java SE、Java EE、Java ME 三者区别
查看>>
灰度图像和彩色图像
查看>>
通过vb.net 和NPOI实现对excel的读操作
查看>>
TCP segmentation offload
查看>>
你必须知道的28个HTML5特征、窍门和技术【转】
查看>>
java数据类型
查看>>
360导航板式
查看>>
闪回恢复区大小不够。报ORA-19809、ORA-19804
查看>>
C#类的构造
查看>>
部署 & virtualen
查看>>
POJ NOI0105-43 质因数分解
查看>>
数据结构——串的朴素模式和KMP匹配算法
查看>>