python下的web服务器模块

简介: python下的web服务模块有三种:   BaseHTTPServer: 提供基本的Web服务和处理器类,分别是HTTPServer和BaseHTTPRequestHandler   SimpleHTTPServer: 包含执行GET和HEAD请求的SimpleHTTPRequestHandler类   CGIHTTPServer: 包含处理POST请求和执行CGIHTTPRequestHandler类。

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']+"\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 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

效果如下:

 

相关文章
|
1天前
|
数据采集 Web App开发 存储
打造高效的Web Scraper:Python与Selenium的完美结合
本文介绍如何使用Python结合Selenium,通过代理IP、设置Cookie和User-Agent抓取BOSS直聘的招聘信息,包括公司名称、岗位、要求和薪资。这些数据可用于行业趋势、人才需求、企业动态及区域经济分析,为求职者、企业和分析师提供宝贵信息。文中详细说明了环境准备、代理配置、登录操作及数据抓取步骤,并提醒注意反爬虫机制和验证码处理等问题。
打造高效的Web Scraper:Python与Selenium的完美结合
|
1月前
|
JSON 安全 中间件
Python Web 框架 FastAPI
FastAPI 是一个现代的 Python Web 框架,专为快速构建 API 和在线应用而设计。它凭借速度、简单性和开发人员友好的特性迅速走红。FastAPI 支持自动文档生成、类型提示、数据验证、异步操作和依赖注入等功能,极大提升了开发效率并减少了错误。安装简单,使用 pip 安装 FastAPI 和 uvicorn 即可开始开发。其优点包括高性能、自动数据验证和身份验证支持,但也存在学习曲线和社区资源相对较少的缺点。
84 15
|
2月前
|
弹性计算 安全 开发工具
灵码评测-阿里云提供的ECS python3 sdk做安全组管理
批量变更阿里云ECS安全组策略(批量变更)
|
3月前
|
开发者 Docker Python
从零开始:使用Docker容器化你的Python Web应用
从零开始:使用Docker容器化你的Python Web应用
110 1
|
3月前
|
JSON 前端开发 API
使用Python和Flask构建简易Web API
使用Python和Flask构建简易Web API
175 3
|
3月前
|
监控 安全 测试技术
如何在实际项目中应用Python Web开发的安全测试知识?
如何在实际项目中应用Python Web开发的安全测试知识?
118 61
|
3月前
|
安全 关系型数据库 测试技术
学习Python Web开发的安全测试需要具备哪些知识?
学习Python Web开发的安全测试需要具备哪些知识?
121 61
|
3月前
|
安全 测试技术 网络安全
如何在Python Web开发中进行安全测试?
如何在Python Web开发中进行安全测试?
|
3月前
|
存储 监控 安全
如何在Python Web开发中确保应用的安全性?
如何在Python Web开发中确保应用的安全性?
|
3月前
|
存储 开发框架 关系型数据库
Python Web开发
Python Web开发

热门文章

最新文章

推荐镜像

更多