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

import 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


免責聲明!

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



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