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

posted @ 2022-02-18 21:00  夕月一弯  阅读(1714)  评论(0编辑  收藏  举报