python下的web服务器模块
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服务器模块的更多相关文章
- python 启动简单web服务器
有时我们在开发web静态页面时,需要一个web服务器来测试. 这时可以利用python提供的web服务器来实现. 1.在命令行下进入某个目录 2.在该目录下运行命令: python -m Simple ...
- CentOS 6.2下搭建Web服务器
1Centos 6.2下搭建web服务器 如今,Linux在Web应用越来越广,许多企业都采用Linux来搭建Web服务器,这样即节省了购买正版软件的费用,而且还能够提高服务器的安全性. 之前我们介绍 ...
- CentOS 6.3下搭建Web服务器
准备前的工作: 1.修改selinux配置文件(/etc/sysconfig/selinux) 关闭防火墙 (1)把SELINUX=enforcing注释掉 (2)并添加SELINUX=disable ...
- Linux下查看Web服务器当前的并发连接数和TCP连接状态
对于web服务器(Nginx.Apache等)来说,并发连接数是一个比较重要的参数,下面就通过netstat命令和awk来查看web服务器的并发连接数以及TCP连接状态. $ netstat -n | ...
- 外网主机访问虚拟机下的Web服务器_服务器应用_Linux公社-Linux系统门户网站
body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...
- ubuntu 下配置Web服务器
ubuntu 下配置Web服务器 1.切换管理员身份 终端/文本界面输入命令: su 根据提示输入密码 注: 如果不能使用su 点击查看如何启用su2.安装MySQL5 apt-get install ...
- 在Win10下搭建web服务器,使用本机IP不能访问,但是使用localhos或127.0.0.1可以正常访问的解决办法
最近在在Win10下搭建web服务器,发现通过windows自带的浏览器win10 edge浏览器使用本机IP不能放问,但是使用localhos或127.0.0.1可以正常访问, 后来无意发现,使用w ...
- python网络-动态Web服务器案例(30)
一.浏览器请求HTML页面的过程 了解了HTTP协议和HTML文档,其实就明白了一个Web应用的本质就是: 浏览器发送一个HTTP请求: 服务器收到请求,生成一个HTML文档: 服务器把HTML文档作 ...
- 用python快速搭建WEB服务器
cmd下进入你要搞WEB项目的目录 输入↓方代码 python -m SimpleHTTPServer 端口号# 默认是8000 这样就启动了一个简单的WEB服务器
随机推荐
- (转)经典线程同步 互斥量Mutex
阅读本篇之前推荐阅读以下姊妹篇: <秒杀多线程第四篇一个经典的多线程同步问题> <秒杀多线程第五篇经典线程同步关键段CS> <秒杀多线程第六篇经典线程同步事件Event& ...
- 在单链表和双链表中删除倒数第K个节点
[说明]: 本文是左程云老师所著的<程序员面试代码指南>第二章中“在单链表和双链表中删除倒数第K个节点”这一题目的C++复现. 本文只包含问题描述.C++代码的实现以及简单的思路,不包含解 ...
- CUG 数学进阶
题目链接:http://acm.cug.edu.cn/JudgeOnline/contest.php?cid=1047 . . . I 题目链接:http://acm.cug.edu.cn/Judge ...
- PHP自练项目之数字分页效果
学习要点:1.LIMIT 用法2.各种参数3.超链接调用 第一:先在文件中设置数字分页模块:我的文件是(blog.php) //分页模块 $_page = $_GET['page']; $_pages ...
- JS 寻找孩子并打印路径
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【LeetCode】Path Sum ---------LeetCode java 小结
Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...
- hdoj 1247 Hat’s Words(字典树)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247 思路分析:题目要求找出在输入字符串中的满足要求(该字符串由输入的字符串中的两个字符串拼接而成)的 ...
- How to setup linked servers for SQL Server and Oracle 64 bit client
感谢作者:Tim Ford. 图文并茂. 原帖地址: http://www.mssqltips.com/sqlservertip/1433/how-to-setup-linked-servers-fo ...
- c#第五次作业---正文提取
1.正文文本 1.正文文本 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFC ...
- iOS Dev (67) 单例的实现
iOS Dev (67) 单例的实现 博客:http://blog.csdn.net/prevention 作者:大锐哥 摘自:Learn iPhone and iPad cocos2d Game D ...