Python用Flask 搭配前端WEB展示數據


前面用爬蟲爬了近幾年房價均值,和用Matplotlib 畫了一個曲線圖

然而直觀的可視化信息一般都是在前端實現交互,下面我們用Python+Web實現一個小的數據展示

HTML代碼

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <link rel="stylesheet" href="static/css/base.css"/>
 7 </head>
 8 <body onload="Onload()">
 9     <div class="head">重慶沙坪壩房價均值</div>
10     <div class="body_right">
11         <label>請輸入年限(2009~2017)</label><input type="text" name="First_year"/><label>請輸入比較年(2009~2017)</label><input type="text" name="Twice_year" /><input type="button" name="Submit" value="Submit"/>
12         <img id="showimg" />
13         
14      </div>
15 </body>
16 </html>
17 <script type="text/javascript">
18     function Onload() {
19         var x = document.getElementsByName("Submit");
20         var First_year = document.getElementsByName("First_year")[0];
21         var Twice_year = document.getElementsByName("Twice_year")[0];
22         x[0].addEventListener("click", function () {
23             AJAX("get", "/find", "first=" + First_year.value + "&tiwce=" + Twice_year.value, 1)
24         });
25     }
26 
27     function AJAX(type, url, datas, state) {
28         var xhr;
29         if (window.XMLHttpRequest) {//除Ie外的瀏覽器
30             xhr = new XMLHttpRequest;
31         } else if (window.ActiveXObject) {//Ie
32             try {
33                 xhr = new ActiveXObject("Msxml2.XMLHTTP");//IE4以下
34             } catch (e) {
35                 xhr = ActiveXObject("Micsoft.XMLHTTP");
36             }
37         }
38         if (type == "get" || type == "GET") {
39             url = url + "?" + datas;
40         }
41         xhr.open(type, url, true);
42         if (type == "post" || type == "POST") {
43             xhr.setRequestHeader("Content-Type", "Application/x-www-form-urlencoded");
44             xhr.send(datas);
45         } else if (type == "get" || type == "GET") {
46             xhr.send(null);
47         } else {
48             return false;
49         }
50         xhr.onreadystatechange = function () {
51             //switch (xhr.readyState) {
52             //         case 1:
53             //             alert("請求已經提出。。。");
54             //             break;
55             //         case 2:
56             //             alert("請求已發送。。。");
57             //             break;
58             //         case 3:
59             //             alert("請求處理中");
60             //             break;
61             //         case 4:
62             //             alert("請求成功");
63             //             alert(xhr.responseText);
64             //             break;
65             //     }
66             if (xhr.readyState == 4 && xhr.status == 200) {
67                 //alert(xhr.responseText);
68                 if (state == 1) {
69                     var jsons = JSON.parse(xhr.responseText);
70                     var show = document.getElementById("showimg");
71                     //alert(jsons.url)   
72                     show.src = jsons.url;
73                 }
74             }
75         }
76     }
77 </script>

我們通過兩個輸入框將想要比較的年份信息通過AJAX異步傳到后台Python,通過后台返回的圖片路徑,讓img標簽起到展示數據的作用

后台Python

 1 mport flask
 2 import pymongo
 3 import matplotlib.pyplot as mp
 4 import re
 5 
 6 client = pymongo.MongoClient('mongodb://localhost:27017')
 7 app = flask.Flask(__name__)
 8 
 9 @app.route('/')
10 def index():
11     return flask.render_template('base.html')
12 @app.route('/find')
13 def find():
14     first = flask.request.args.get('first')
15     twice = flask.request.args.get('tiwce')
16     firstTime = list(client['HousePrice']['CQ'].find({'dateTime':re.compile(first)}))
17     twiceTime = list(client['HousePrice']['CQ'].find({'dateTime': re.compile(twice)}))
18     MapOnex = []
19     MapOney = []
20     MapTwox = []
21     MapTwoy = []
22     for i in firstTime:
23         MapOnex.append(i['dateTime'][5:8])
24         MapOney.append(int(i['housePrice'][0:4]))
25     for i in twiceTime:
26         MapTwox.append(i['dateTime'][5:8])
27         MapTwoy.append(int(i['housePrice'][0:4]))
28     mp.title('CQSPBHousePrice')
29     mp.xlabel('Month')
30     mp.ylabel('Price')
31     mp.plot(MapOnex,MapOney, label = 'year:'+first)
32     mp.plot(MapTwox, MapTwoy, label='year:' + twice)
33     mp.legend(bbox_to_anchor=[0.5,1])
34     mp.grid()
35     mp.savefig('E:\Practice\CQHousePrice\static\IMG/'+first+'-'+ twice +'.png')
36     mp.close()
37     return flask.json.dumps({'url': '/static/IMG/'+first+'-'+twice +'.png'})
38 if __name__ == '__main__':
39     app.run('localhost', 5000)

這里通過前端傳來的兩個年份信息,我們經行一個模糊查詢,並將數據信息畫成圖,存入文件,通過JSON數組

將文件路徑返回給前端JS,實現簡單的Web與Python的交互,將數據可視化

 

效果圖:

若您有改進建議或者問題,請在評論區指出

  謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM