python教学4
python教学4
1.新建项目
选择python,选择项目的创建路径
添加一个python文件和HTML文件
导入.js文件(文件需要去群上查找)
这里是所有的文件
2.学习python之BaseHTTPServer模块
1.py代码如下
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
host = ('0.0.0.0', 14730) # 绑定地址和端口号
a = {
"a": {
"code": "200", # 状态码
"flushTime": "123456", # 刷新时间
"description": "null", # 描述
"status": 1 # 状态(0/1)
},
"b": {
"code": "400",
"flushTime": "123456789",
"description": "22222",
"status": 0
},
"c": {
"code": "404",
"flushTime": "1234567890",
"description": "66666",
"status": 0
},
}
class HTTPRequest(BaseHTTPRequestHandler):
def do_GET(self):
print(self)
self.send_response(200) # 设置返回的状态码
self.send_header('Content-type', 'text/html') # html
self.end_headers() # 结束请求头
path = self.path
if path == '/':
f = open('index.html', 'r', encoding='utf8')
self.wfile.write(f.read().encode())
elif path == '/jquery':
self.send_header('content-type', 'text/javascript')
f = open('jquery.js', 'r', encoding='utf8')
self.wfile.write(f.read().encode())
elif path == '/get':
self.wfile.write(json.dumps(a).encode())
server = HTTPServer(host, HTTPRequest)
server.serve_forever()
index.html代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title23333</title>
<script src="/jquery" type="text/javascript"></script>
</head>
<body>
1
<table border="1">
<tbody id="table"></tbody>
</table>
<script>
//设置属性
var setAttr = function (el, attr) {
for (var i in attr) {
if (typeof attr[i] === "string") {
el[i] = attr[i];
} else if (typeof attr[i] === "object") {
setAttr(el[i], attr[i]);
}
}
};
//创建元素
var $$ = function (el, attr, parent) {
var _el = document.createElement(el);
setAttr(_el, attr);
parent.appendChild(_el);
return _el;
};
var getData = function(){
$.ajax({
url:"/get",
success:function (res) {
res = JSON.parse(res);
var table = $("#table")[0];
table.innerHTML = "";
var _tr =$$("tr", {}, table);
$$("th", {"innerHTML": "地址"}, _tr);
$$("th", {"innerHTML": "描述"}, _tr);
$$("th", {"innerHTML": "状态"}, _tr);
$$("th", {"innerHTML": "状态码"}, _tr);
$$("th", {"innerHTML": "上次刷新时间"}, _tr);
for(var i in res){
console.log(i);
var tr = $$("tr", {}, table);
$$("td", {"innerHTML": i}, tr);
$$("td", {"innerHTML": res[i].description}, tr);
$$("td", {"innerHTML": res[i].status.toString()}, tr);
$$("td", {"innerHTML": res[i].code}, tr);
$$("td", {"innerHTML": res[i].flushTime}, tr);
}
//alert(res); #弹窗
}
});
};
window.onload = function () {
getData();
}
</script>
</body>
</html>
右键.py文件,运行
后面进行测试可以点击这个按钮进行刷新
运行成功
3.测试
打开浏览器访问绑定的IP地址和端口
这里是访问127.0.0.1:14730