python下的web服务模块有三种:
BaseHTTPServer: 提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler
SimpleHTTPServer: 包含执行GET和HEAD请求的SimpleHTTPRequestHandler类
CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类。
下面是CGIHTTPServer类示例:
root@u254:~/cp# tree
.
|-- cgi-bin
| |-- get_info.py
| |-- get_info.pyc
| `-- hick.py
`-- http.py http.py
#!/usr/bin/python
#encoding=utf-8
#supported by python2.7 import sys
from CGIHTTPServer import CGIHTTPRequestHandler
from BaseHTTPServer import HTTPServer
server_addr = ('192.168.2.18', 20014)
httpd = HTTPServer(server_addr, CGIHTTPRequestHandler)
httpd.serve_forever() hick.py
#!/usr/bin/python
#encoding=utf-8
#supported python2.7 import cgi
import sys
form = cgi.FieldStorage()
name = form["access"].value #获取get传递的参数 print "HTTP/1.0 200 OK"
print "Content-Type:text/html"
print ""
print ""
print "name %s"% name
print ""
执行效果图如下:
SimpleHTTPServer示例:
root@u254:~/cp# tree
.
|-- get_info.py
|-- get_info.pyc
`-- http2.py get_info.py如下:
#!/usr/bin/python
#encoding=utf-8
#supported python2.7 import commands
import json def GetInfo(id):
cmd = "radosgw-admin -c /etc/ceph/ceph.conf bucket stats --uid="+ str(id) +" --categories={}"
#cmd = "radosgw-admin bucket stats --uid=37 --categories={} --access=radosgw-admin --access-key=37 --secret=IXJcIub8Zprn7Vu+Tm3VId0LdrnMCfgpZ6sSb9zc"
dict_t = {}
content = commands.getoutput(cmd)
#print content
if content.find(")") != -1:
en_json = json.loads(content.split(')')[1])
else:
en_json = json.loads(content)
for element in en_json:
if "bucket" in element.keys() and "usage" in element.keys():
#print element["bucket"]
if "rgw.main" in element["usage"].keys() and "size_kb_actual" in element["usage"]["rgw.main"].keys():
#print element["usage"]["rgw.main"]["size_kb_actual"]
dict_t.setdefault(element["bucket"], element["usage"]["rgw.main"]["size_kb_actual"])
else:
dict_t.setdefault(element["bucket"], 0)
#print json.dumps(dict_t)
return json.dumps(dict_t) if __name__ == "__main__":
GetInfo(37) http2.py如下:
#!/usr/bin/pyton
#encoding=utf-8
#supported by python2.7 #encoding=utf-8
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import io,shutil
import urllib,time
import sys
sys.path.append(r'./')
import getopt,string
import get_info 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:
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]:
queryParams = {}
for qp in query[1].split('&'):
kv = qp.split('=')
print kv[1]
kv[1] = get_info.GetInfo(kv[1])
queryParams[kv[0]] = urllib.unquote(kv[1]).decode("utf-8", 'ignore')
#content+= kv[0]+':'+queryParams[kv[0]]+"\r\n"
content+= 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)
def transDicts(params):
dicts={}
if len(params)==0:
return
params = params.split('&')
for param in params:
dicts[param.split('=')[0]]=param.split('=')[1]
return dicts if __name__=='__main__':
try:
server = HTTPServer(('203.156.196.254', 20014), MyRequestHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
pass
效果如下: