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

时间:2022-06-23 05:24:14

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

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

前台html:

 <!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<p>this is a test page!</p>
<button onclick="get()">click</button>
<div id="result"></div>
<script src="libs\jquery-3.2.1.min.js"></script>
<script>
function get(){
//alert("test");
$.ajax({
url:"BaseInfo",
data:{id:123,name:"xiaoming"},
success:function(e){
$("#result").html(e);
}})
}
</script>
</body>
</html>

python代码:

 #!coding:utf8
import BaseHTTPServer
import CGIHTTPServer
import SimpleHTTPServer
import SocketServer
import urllib
import io
import shutil PORT=8000 #定义数据处理模块--此部分可放于外部引用文件
class dataHandler():
#接口分发
def run(self,path,args):
index = path.replace("/","")
switch={
"BaseInfo": self.getBaseInfo,
"Monitor": self.getMonitor
}
return switch[index](args)
#接口具体实现
def getBaseInfo(self,args):
return "BaseInfo:"+args
def getMonitor(self,args):
return "Monitor"+args #服务环境搭建
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
mpath,margs=urllib.splitquery(self.path) # ?分割
if margs==None:
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
else:
self.do_action(mpath, margs)
def do_POST(self):
mpath,margs=urllib.splitquery(self.path)
datas = self.rfile.read(int(self.headers['content-length']))
self.do_action(mpath, datas)
#请求处理方法
def do_action(self, path, args):
dh = dataHandler()
result = dh.run(path, args)
self.outputtxt(result)
#数据返回到前台
def outputtxt(self, content):
#指定返回编码
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)
#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) #web服务主程序
httpd = SocketServer.TCPServer(("", PORT), ServerHandler)
print "serving at port", PORT
httpd.serve_forever()

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