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

效果如下:

python下的web服务器模块的更多相关文章

  1. python 启动简单web服务器

    有时我们在开发web静态页面时,需要一个web服务器来测试. 这时可以利用python提供的web服务器来实现. 1.在命令行下进入某个目录 2.在该目录下运行命令: python -m Simple ...

  2. CentOS 6.2下搭建Web服务器

    1Centos 6.2下搭建web服务器 如今,Linux在Web应用越来越广,许多企业都采用Linux来搭建Web服务器,这样即节省了购买正版软件的费用,而且还能够提高服务器的安全性. 之前我们介绍 ...

  3. CentOS 6.3下搭建Web服务器

    准备前的工作: 1.修改selinux配置文件(/etc/sysconfig/selinux) 关闭防火墙 (1)把SELINUX=enforcing注释掉 (2)并添加SELINUX=disable ...

  4. Linux下查看Web服务器当前的并发连接数和TCP连接状态

    对于web服务器(Nginx.Apache等)来说,并发连接数是一个比较重要的参数,下面就通过netstat命令和awk来查看web服务器的并发连接数以及TCP连接状态. $ netstat -n | ...

  5. 外网主机访问虚拟机下的Web服务器_服务器应用_Linux公社-Linux系统门户网站

    body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...

  6. ubuntu 下配置Web服务器

    ubuntu 下配置Web服务器 1.切换管理员身份 终端/文本界面输入命令: su 根据提示输入密码 注: 如果不能使用su 点击查看如何启用su2.安装MySQL5 apt-get install ...

  7. 在Win10下搭建web服务器,使用本机IP不能访问,但是使用localhos或127.0.0.1可以正常访问的解决办法

    最近在在Win10下搭建web服务器,发现通过windows自带的浏览器win10 edge浏览器使用本机IP不能放问,但是使用localhos或127.0.0.1可以正常访问, 后来无意发现,使用w ...

  8. python网络-动态Web服务器案例(30)

    一.浏览器请求HTML页面的过程 了解了HTTP协议和HTML文档,其实就明白了一个Web应用的本质就是: 浏览器发送一个HTTP请求: 服务器收到请求,生成一个HTML文档: 服务器把HTML文档作 ...

  9. 用python快速搭建WEB服务器

    cmd下进入你要搞WEB项目的目录 输入↓方代码 python -m SimpleHTTPServer 端口号# 默认是8000 这样就启动了一个简单的WEB服务器

随机推荐

  1. error C2018: unknown character '0xa1'

    调试程序时出现 error C2018: unknown character '0xa1',代码行中加入的有编译器不能识别的字符,才发现由空格引起的,删除掉就ok了.

  2. Google地图,Baidu地图数据供应商

    http://janwen.iteye.com/blog/488659 Google百度  我老以为百度,Google的地图产品是自己开发的,原来是别人提供的数据, 百度的数据提供商有 北京世纪高通科 ...

  3. Windows下安装Apache2.4+PHP5.4+Mysql5.7

    注:文中所写的安装过程均在Win7 x86下通过测试,提供的百度云下载链接均为32位安装包,如需Apache和PHP的64位安装包请从官网下载! 一.安装Apache2.4.12 Apache官方下载 ...

  4. php 不能同时提交form

    注意:提交form到相应的页面时,不能在form中嵌套一个form,否则,不能提交

  5. (Problem 53)Combinatoric selections

    There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 2 ...

  6. BZOJ 1087 互不侵犯King (位运算)

    题解:首先,这道题可以用位运算来表示每一行的状态,同八皇后的搜索方法,然后对于限制条件不相互攻击,则只需将新加入的一行左右移动与上一行相&,若是0则互不攻击,方案可行.对于每种方案,则用递推来 ...

  7. BZOJ 1874 取石子游戏 (NIM游戏)

    题解:简单的NIM游戏,直接计算SG函数,至于找先手策略则按字典序异或掉,去除石子后再异或判断,若可行则直接输出. #include <cstdio> const int N=1005; ...

  8. Oracle select into from 和 insert into select

    select into from SQLSERVER  创建表: select * into aaa from bbb Oracle 创建表: create table aaa as select * ...

  9. Laravel + Xdebug 时需要注意的问题

    [平台环境]64bit Win7 + Wamp2.5 (php 5.5, Apache 2.4.9) [Xdebug版本]php_xdebug-2.2.5-5.5-vc11-x86_64.dll 配置 ...

  10. HDOJ 1429 胜利大逃亡(续) (bfs+状态压缩)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1429 思路分析:题目要求找出最短的逃亡路径,但是与一般的问题不同,该问题增加了门与钥匙约束条件: 考虑 ...