1 # -*- coding: utf-8 -*-
2 from flask import Flask, jsonify
3 import psutil, time,json
4
5 app = Flask(__name__)#实例化app对象
6
7 @app.route(‘/test_post/aa‘, methods=[‘GET‘,‘POST‘])#路由
8 def test_post():
9
10 memKeys = ["total", "available", "percent", "used", "free"]#查看内存信息
11 memVaules = psutil.virtual_memory()
12 memInfo = dict(zip(memKeys, memVaules))
13 memInfo = {k: str(v / pow(1024.0, 3)) + ‘GB‘ for k,
14 v in memInfo.items() if k != ‘percent‘}
15 memInfo[‘percent‘] = psutil.virtual_memory().percent
16 return "successCallback"+"("+json.dumps(memInfo)+")"#将结果以json形式返回,通过jsonp与前台交互
17
18
19
20 if __name__ == "__main__":
21 app.run(
22 host = ‘0.0.0.0‘,#任何ip都可以访问
23 port = 7777,#端口
24 debug = True
25 )
接下来是前台代码
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(‘#search‘).click(function () {
$.ajax({
type: ‘GET‘,
url: ‘http://192.168.1.106:7777/test_post/aa‘,
dataType: ‘jsonp‘, //希望服务器返回json格式的数据
jsonp: "callback",
jsonpCallback: "successCallback",//回调方法
success: function (data) {
console.log(data);
}
});
});
</script>
接下来就可以看到控制台数据了
原文:http://www.cnblogs.com/shiluoliming/p/7143224.html