Python搭建Web服务器,与Ajax交互,接收处理Get和Post请求的简易结构

用python搭建web服务器,与ajax交互,接收处理Get和Post请求;简单实用,没有用框架,适用于简单需求,更多功能可进行扩展。

python有自带模块BaseHTTPServer、CGIHTTPServer、SimpleHTTPServer,详细功能可参考API

前台html:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <title>test</title>
 5     </head>
 6     <body>
 7         <h1>test</h1>
 8         <p>this is a test page!</p>
 9         <button onclick="get()">click</button>
10         <div id="result"></div>
11         <script src="libsjquery-3.2.1.min.js"></script>
12         <script>
13             function get(){
14                 //alert("test");
15                 $.ajax({
16                     url:"BaseInfo",
17                     data:{id:123,name:"xiaoming"},
18                     success:function(e){
19                         $("#result").html(e);
20                 }})
21             }
22         </script>
23     </body>
24 </html>

python代码:

 1 #!coding:utf8
 2 import BaseHTTPServer
 3 import CGIHTTPServer
 4 import SimpleHTTPServer
 5 import SocketServer
 6 import urllib
 7 import io
 8 import shutil
 9 
10 PORT=8000
11 
12 #定义数据处理模块--此部分可放于外部引用文件
13 class dataHandler():
14     #接口分发
15     def run(self,path,args):
16         index = path.replace("/","")
17         switch={
18             "BaseInfo": self.getBaseInfo,
19             "Monitor": self.getMonitor
20             }
21         return switch[index](args)
22     #接口具体实现
23     def getBaseInfo(self,args):
24         return "BaseInfo:"+args
25     def getMonitor(self,args):
26         return "Monitor"+args
27 
28 #服务环境搭建
29 class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): 
30     def do_GET(self):  
31         mpath,margs=urllib.splitquery(self.path) # ?分割
32         if margs==None:
33             SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
34         else:
35             self.do_action(mpath, margs) 
36     def do_POST(self): 
37         mpath,margs=urllib.splitquery(self.path)
38         datas = self.rfile.read(int(self.headers['content-length']))
39         self.do_action(mpath, datas)
40     #请求处理方法
41     def do_action(self, path, args):
42         dh = dataHandler()
43         result = dh.run(path, args)
44         self.outputtxt(result)
45     #数据返回到前台
46     def outputtxt(self, content):
47         #指定返回编码
48         enc = "UTF-8"
49         content = content.encode(enc)          
50         f = io.BytesIO()
51         f.write(content)
52         f.seek(0)  
53         self.send_response(200)  
54         self.send_header("Content-type", "text/html; charset=%s" % enc)  
55         self.send_header("Content-Length", str(len(content)))  
56         self.end_headers()  
57         shutil.copyfileobj(f,self.wfile)
58         #SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) 
59 
60 #web服务主程序
61 httpd = SocketServer.TCPServer(("", PORT), ServerHandler) 
62 print "serving at port", PORT 
63 httpd.serve_forever() 

部分代码内容参考网友,整理仅供学习交流,欢迎留言交流。

原文地址:https://www.cnblogs.com/fanlu/p/8038169.html