flask 数据可视化图形

     

目录

1、如何开始一个flask系统

2、登录注册

3、牛奶面包折线图

4、echarts可视化图像

1. 创建一个【page.html】(柱形图)部分

2. 创建一个【login.html】登录部分

3. 创建一个【page2.html】牛奶面包的折线图部分

前言:    

    本文的学习需要读者有一定的Flask的知识基础,初学者请先自学完成Flask简易项目搭建。Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。

1、如何开始一个flask系统

在命令中pip安装一个flask,就可以直接开始一个flask系统了。

pip install flask

在 运行py文件会遇到很多报错,部分原因是没有选择对环境。

因为我弄的是牛奶和面包的销量数据我直接导入了文件

 创建一个app.py文件,一个简单的flask应用。

from flask import Flask, request, redirect, render_template, session, jsonify

import pandas as pd

df = pd.read_excel(r'g:\数据可视化及开发python\15-flask开发基础\flask\demo1\折线图作业数据-商品销量(1).xlsx')
df['时间'] = df['日期'].agg(lambda x:str(x) [5:10])
dict_to_json = {
    'time':df['时间'].tolist(),
    'milk':df['牛奶'].tolist(),
    'bread':df['面包'].tolist(),
}
app = Flask(__name__)

除了一个基础的app之外,还需要静态文件(static):一些不会变更的css,js,img文件,还有html文件(templates)

 

所以一个基础的flask应用如下:

2、登录注册

登录账号密码

对用户信息加密

app.secret_key = 'QWERTYUIOP'  # 对用户信息加密

@app.route('/login', methods=['GET', "POST"])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'admin' and pwd == '123':
        session['user_info'] = user
        return redirect('/page')
    elif user == 'admin' and pwd =='123':
        session['user_info'] = user
        return redirect('/page2')
    else:
        return render_template('login.html', msg='用户名或密码输入错误')

3、牛奶面包折线图

@app.route('/page')
def index():
    data = {
        'x':['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        'y':[260, 150, 230, 224, 218, 135, 147]
    }
    return render_template('page.html',**data)
# 定义一个路由存储json数据
@app.route('/json')
def json():
    
    return jsonify(dict_to_json) # jsonify中传入一个字典

# 定义一个路由展示图行
@app.route('/page2')
def page2():
    return render_template('page2.html')

if __name__ == "__main__":
    # app.run('0.0.0.0',port=80)
    app.run()
print(dict_to_json)

        app.py合并后的代码

from flask import Flask, request, redirect, render_template, session, jsonify

import pandas as pd

df = pd.read_excel(r'g:\数据可视化及开发python\15-flask开发基础\flask\demo1\折线图作业数据-商品销量(1).xlsx')
df['时间'] = df['日期'].agg(lambda x:str(x) [5:10])
dict_to_json = {
    'time':df['时间'].tolist(),
    'milk':df['牛奶'].tolist(),
    'bread':df['面包'].tolist(),
}
app = Flask(__name__)



app.secret_key = 'QWERTYUIOP'  # 对用户信息加密

@app.route('/login', methods=['GET', "POST"])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    user = request.form.get('user')
    pwd = request.form.get('pwd')
    if user == 'admin' and pwd == '123':
        session['user_info'] = user
        return redirect('/page')
    elif user == 'admin' and pwd =='123':
        session['user_info'] = user
        return redirect('/page2')
    else:
        return render_template('login.html', msg='用户名或密码输入错误')
    
    

@app.route('/page')
def index():
    data = {
        'x':['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        'y':[260, 150, 230, 224, 218, 135, 147]
    }
    return render_template('page.html',**data)
# 定义一个路由存储json数据
@app.route('/json')
def json():
    
    return jsonify(dict_to_json) # jsonify中传入一个字典

# 定义一个路由展示图行
@app.route('/page2')
def page2():
    return render_template('page2.html')

if __name__ == "__main__":
    # app.run('0.0.0.0',port=80)
    app.run()
print(dict_to_json)

4、echarts可视化图像

可视化有很多种方法,但是最省力的之一,一定是直接使用echarts:echarts的代码可以直接复制过来用,经过简单的修改就可以实现非常好看的效果。

可视化图像

 可以参考网页中建立一个基础的可视化的页面。

1. 创建一个【page.html】(柱形图)部分

渲染效果:

        给模板中添加数据使其变得更见美观,做到渲染效果。

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>bar</title>
    <!-- <script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script> -->
    <script type="text/javascript" src="../static/js/echarts.min.js"></script>
</head>

<body>
    <h2>{{x}}</h2>
    <h2>{{y}}</h2>
    <div id="chart" style="width:900; height:500px;"></div>
    <script type='text/javascript'>
        // var chartDom = document.getElementById('chart');
        var myChart = echarts.init(document.getElementById('chart'));
        var option;
        
        option = {
            xAxis: {
                type: 'category',
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: [260, 150, 230, 224, 218, 135, 147],
                    type: 'bar'
                },
            ]
        };
        myChart.setOption(option);
        console.log(x);
    </script>
</body>

</html>

2. 创建一个【login.html】登录部分


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <style>
        .loginForm {
            /*边框高度*/
            height: 300px;
            /*边框宽度*/
            width: 500px;
            /*边框颜色*/
            border: #4d4d4d solid 1px;
            /*边框圆角*/
            border-radius: 4px;
            /*阴影 水平方向,竖直方向,模糊距离*/
            box-shadow: 5px 5px 5px #4d4d4d;
            /*上边界距离*/
            margin-top: 150px;
            /*左边界距离:自动*/
            margin-left: auto;
            /*右边界距离:自动*/
            margin-right: auto;
            /*用户名、密码间距*/
            padding: 20px 40px;
        }

        /*将用户登录置于中间*/
        .loginForm h2 {
            text-align: center;
        }

        .button {
            text-align: center;
            vertical-align: middle;
        }
    </style>
</head>
<body>
<div class="loginForm">
    <h2>平台登录界面</h2>
    <form method="post">
        <div class="form-group">
            <label>用户名</label>
            <input type="text" class="form-control" name="user" placeholder="请输入用户名">
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" class="form-control" name="pwd" placeholder="请输入密码">
        </div>
        <div class="button">
            <input type="submit" class="btn btn-primary" value="登 录"/>
        </div>
    </form>
</div>

</body>
</html>

3. 创建一个【page2.html】牛奶面包的折线图部分

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Awesome-pyecharts</title>
                <script type="text/javascript" src="https://assets.pyecharts.org/assets/v5/echarts.min.js"></script>

</head>
<body >
    <div id="4908dbf047b244aea5a10ff9a82d2dd2" class="chart-container" style="width:900px; height:500px; "></div>
    <script>
        var chart_4908dbf047b244aea5a10ff9a82d2dd2 = echarts.init(
            document.getElementById('4908dbf047b244aea5a10ff9a82d2dd2'), 'white', {renderer: 'canvas'});
        var option_4908dbf047b244aea5a10ff9a82d2dd2 = {
    "backgroundColor": "white",
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "aria": {
        "enabled": false
    },
    "color": [
        "#5470c6",
        "#91cc75",
        "#fac858",
        "#ee6666",
        "#73c0de",
        "#3ba272",
        "#fc8452",
        "#9a60b4",
        "#ea7ccc"
    ],
    "series": [
        {
            "type": "line",
            "name": "\u9762\u5305",
            "connectNulls": false,
            "xAxisIndex": 0,
            "symbolSize": 4,
            "showSymbol": true,
            "smooth": false,
            "clip": true,
            "step": false,
            "data": [
                [
                    "05-01",
                    80
                ],
                [
                    "05-02",
                    77
                ],
                [
                    "05-03",
                    51
                ],
                [
                    "05-04",
                    57
                ],
                [
                    "05-05",
                    65
                ],
                [
                    "05-06",
                    78
                ],
                [
                    "05-07",
                    58
                ],
                [
                    "05-08",
                    66
                ],
                [
                    "05-09",
                    51
                ],
                [
                    "05-10",
                    73
                ],
                [
                    "05-11",
                    79
                ],
                [
                    "05-12",
                    52
                ],
                [
                    "05-13",
                    91
                ],
                [
                    "05-14",
                    56
                ],
                [
                    "05-15",
                    80
                ],
                [
                    "05-16",
                    45
                ],
                [
                    "05-17",
                    58
                ],
                [
                    "05-18",
                    81
                ],
                [
                    "05-19",
                    57
                ],
                [
                    "05-20",
                    82
                ],
                [
                    "05-21",
                    64
                ],
                [
                    "05-22",
                    85
                ],
                [
                    "05-23",
                    68
                ],
                [
                    "05-24",
                    88
                ],
                [
                    "05-25",
                    63
                ],
                [
                    "05-26",
                    48
                ],
                [
                    "05-27",
                    67
                ],
                [
                    "05-28",
                    53
                ],
                [
                    "05-29",
                    56
                ],
                [
                    "05-30",
                    75
                ],
                [
                    "05-31",
                    85
                ]
            ],
            "hoverAnimation": true,
            "label": {
                "show": true,
                "margin": 8
            },
            "logBase": 10,
            "seriesLayoutBy": "column",
            "lineStyle": {
                "show": true,
                "width": 1,
                "opacity": 1,
                "curveness": 0,
                "type": "solid"
            },
            "areaStyle": {
                "opacity": 0
            },
            "markPoint": {
                "label": {
                    "show": true,
                    "position": "inside",
                    "color": "#fff",
                    "margin": 8
                },
                "data": [
                    {
                        "type": "min"
                    }
                ]
            },
            "zlevel": 0,
            "z": 0
        },
        {
            "type": "line",
            "name": "\u725b\u5976",
            "connectNulls": false,
            "xAxisIndex": 0,
            "symbol": "traingle",
            "symbolSize": 6,
            "showSymbol": true,
            "smooth": false,
            "clip": true,
            "step": false,
            "data": [
                [
                    "05-01",
                    53
                ],
                [
                    "05-02",
                    60
                ],
                [
                    "05-03",
                    84
                ],
                [
                    "05-04",
                    72
                ],
                [
                    "05-05",
                    81
                ],
                [
                    "05-06",
                    66
                ],
                [
                    "05-07",
                    78
                ],
                [
                    "05-08",
                    64
                ],
                [
                    "05-09",
                    96
                ],
                [
                    "05-10",
                    82
                ],
                [
                    "05-11",
                    49
                ],
                [
                    "05-12",
                    42
                ],
                [
                    "05-13",
                    50
                ],
                [
                    "05-14",
                    72
                ],
                [
                    "05-15",
                    65
                ],
                [
                    "05-16",
                    81
                ],
                [
                    "05-17",
                    77
                ],
                [
                    "05-18",
                    66
                ],
                [
                    "05-19",
                    85
                ],
                [
                    "05-20",
                    79
                ],
                [
                    "05-21",
                    76
                ],
                [
                    "05-22",
                    70
                ],
                [
                    "05-23",
                    79
                ],
                [
                    "05-24",
                    81
                ],
                [
                    "05-25",
                    59
                ],
                [
                    "05-26",
                    49
                ],
                [
                    "05-27",
                    66
                ],
                [
                    "05-28",
                    85
                ],
                [
                    "05-29",
                    72
                ],
                [
                    "05-30",
                    59
                ],
                [
                    "05-31",
                    65
                ]
            ],
            "hoverAnimation": true,
            "label": {
                "show": true,
                "margin": 8
            },
            "logBase": 10,
            "seriesLayoutBy": "column",
            "lineStyle": {
                "show": true,
                "width": 1,
                "opacity": 1,
                "curveness": 0,
                "type": "solid",
                "color": "#44cef6"
            },
            "areaStyle": {
                "opacity": 0
            },
            "markPoint": {
                "label": {
                    "show": true,
                    "position": "inside",
                    "color": "#fff",
                    "margin": 8
                },
                "data": [
                    {
                        "type": "max"
                    }
                ]
            },
            "itemStyle": {
                "color": "#e4c6d0",
                "borderColor": "#a4e2c6",
                "borderWidth": 1
            },
            "zlevel": 0,
            "z": 0
        }
    ],
    "legend": [
        {
            "data": [
                "\u9762\u5305",
                "\u725b\u5976"
            ],
            "selected": {}
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "item",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "line"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "enterable": false,
        "confine": false,
        "appendToBody": false,
        "transitionDuration": 0.4,
        "textStyle": {
            "fontSize": 14
        },
        "borderWidth": 0,
        "padding": 5,
        "order": "seriesAsc"
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "gridIndex": 0,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": true,
                    "width": 1,
                    "opacity": 1,
                    "curveness": 0,
                    "type": "solid"
                }
            },
            "data": [
                "05-01",
                "05-02",
                "05-03",
                "05-04",
                "05-05",
                "05-06",
                "05-07",
                "05-08",
                "05-09",
                "05-10",
                "05-11",
                "05-12",
                "05-13",
                "05-14",
                "05-15",
                "05-16",
                "05-17",
                "05-18",
                "05-19",
                "05-20",
                "05-21",
                "05-22",
                "05-23",
                "05-24",
                "05-25",
                "05-26",
                "05-27",
                "05-28",
                "05-29",
                "05-30",
                "05-31"
            ]
        }
    ],
    "yAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "gridIndex": 0,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "splitLine": {
                "show": true,
                "lineStyle": {
                    "show": true,
                    "width": 1,
                    "opacity": 1,
                    "curveness": 0,
                    "type": "solid"
                }
            }
        }
    ]
};
        chart_4908dbf047b244aea5a10ff9a82d2dd2.setOption(option_4908dbf047b244aea5a10ff9a82d2dd2);
    </script>
</body>
</html>

最后运行app.py结果:

复制该网站进入浏览器中运行,在http://127.0.0.1:5000/后面添加l(login)、(page)、(page2)就能分别出现柱形图、登录页面、折线图。

 

小结

        本小节,介绍了 Flask Web 框架的主要特性、官方网站、源码资源、体系结构、安装部署和常用插件,并通过一个示例程序给演示了 Flask 的基本应用。

  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值