1. 程式人生 > 其它 >Python用Flask 搭配前端WEB展示資料

Python用Flask 搭配前端WEB展示資料

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

然而直觀的視覺化資訊一般都是在前端實現互動,下面我們用Python+Web實現一個小的資料展示

HTML程式碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="static/css/base.css"/>
</head>
<body onload="Onload()"
> <div class="head">重慶沙坪壩房價均值</div> <div class="body_right"> <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"/> <img id="showimg" /> </div> </body> </html> <script type="text/javascript"> function Onload() { var x = document.getElementsByName("Submit"); var First_year = document.getElementsByName("First_year")[0]; var Twice_year
= document.getElementsByName("Twice_year")[0]; x[0].addEventListener("click", function () { AJAX("get", "/find", "first=" + First_year.value + "&tiwce=" + Twice_year.value, 1) }); } function AJAX(type, url, datas, state) { var xhr; if (window.XMLHttpRequest) {//除Ie外的瀏覽器 xhr = new XMLHttpRequest; } else if (window.ActiveXObject) {//Ie try { xhr = new ActiveXObject("Msxml2.XMLHTTP");//IE4以下 } catch (e) { xhr = ActiveXObject("Micsoft.XMLHTTP"); } } if (type == "get" || type == "GET") { url = url + "?" + datas; } xhr.open(type, url, true); if (type == "post" || type == "POST") { xhr.setRequestHeader("Content-Type", "Application/x-www-form-urlencoded"); xhr.send(datas); } else if (type == "get" || type == "GET") { xhr.send(null); } else { return false; } xhr.onreadystatechange = function () { //switch (xhr.readyState) { // case 1: // alert("請求已經提出。。。"); // break; // case 2: // alert("請求已傳送。。。"); // break; // case 3: // alert("請求處理中"); // break; // case 4: // alert("請求成功"); // alert(xhr.responseText); // break; // } if (xhr.readyState == 4 && xhr.status == 200) { //alert(xhr.responseText); if (state == 1) { var jsons = JSON.parse(xhr.responseText); var show = document.getElementById("showimg"); //alert(jsons.url) show.src = jsons.url; } } } } </script>

通過兩個輸入框將想要比較的年份資訊通過AJAX非同步傳到後臺Python,通過後臺返回的圖片路徑,讓img標籤起到展示資料的作用

後臺Python

mport flask
import pymongo
import matplotlib.pyplot as mp
import re

client = pymongo.MongoClient('mongodb://localhost:27017')
app = flask.Flask(__name__)

@app.route('/')
def index():
    return flask.render_template('base.html')
@app.route('/find')
def find():
    first = flask.request.args.get('first')
    twice = flask.request.args.get('tiwce')
    firstTime = list(client['HousePrice']['CQ'].find({'dateTime':re.compile(first)}))
    twiceTime = list(client['HousePrice']['CQ'].find({'dateTime': re.compile(twice)}))
    MapOnex = []
    MapOney = []
    MapTwox = []
    MapTwoy = []
    for i in firstTime:
        MapOnex.append(i['dateTime'][5:8])
        MapOney.append(int(i['housePrice'][0:4]))
    for i in twiceTime:
        MapTwox.append(i['dateTime'][5:8])
        MapTwoy.append(int(i['housePrice'][0:4]))
    mp.title('CQSPBHousePrice')
    mp.xlabel('Month')
    mp.ylabel('Price')
    mp.plot(MapOnex,MapOney, label = 'year:'+first)
    mp.plot(MapTwox, MapTwoy, label='year:' + twice)
    mp.legend(bbox_to_anchor=[0.5,1])
    mp.grid()
    mp.savefig('E:\Practice\CQHousePrice\static\IMG/'+first+'-'+ twice +'.png')
    mp.close()
    return flask.json.dumps({'url': '/static/IMG/'+first+'-'+twice +'.png'})
if __name__ == '__main__':
    app.run('localhost', 5000)

這裡通過前端傳來的兩個年份資訊,我們經行一個模糊查詢,並將資料資訊畫成圖,存入檔案,通過JSON陣列

將檔案路徑返回給前端JS,實現簡單的Web與Python的互動,將資料視覺化

效果圖:

轉載:https://www.cnblogs.com/HaoYu-StudyNote/p/8657078.html