第七讲:flask框架

本文介绍了如何使用Flask框架进行Python web开发,包括其灵活性、轻便性,以及蓝图、模板引擎和数据库扩展的使用实例。通过Flask构建新闻和产品页面,展示了如何集成Pyecharts进行数据可视化和文件上传功能。
摘要由CSDN通过智能技术生成

python之flask框架:


flask图标

简介

Flask是一个轻量级的基于Python的web框架。
Flask是一个轻量级的可定制框架,使用Python语言编写,较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。

优势

一、后续的基于机器学习的车辆检测与属性识别算法研究,主要开发语言也是应用Python,整个系统统一开发语言,便于开发和后期维护。
二、Flask因为灵活、轻便且高效的特点被业界认可,同时拥有基于Werkzeug、Jinja2等一些开源库,拥有内置服务器和单元测试,适配RESTful,支持安全的cookies,而且官方文档完整,便于学习掌握。
三、Flask中拥有灵活的Jinja2模板引擎,提高了前端代码的复用率。这样可以提高开发效率和有利于后期开发与维护。在现有标准中,Flask算是微小型框架。Flask有两个主要依赖:路由、调试和Web服务器网关接口(WebServerGatewayInterface,WSGI)子系统由Werkzeug提供;模板系统由Jinja2提供。Werkzeug和Jinja2都是由Flask的核心开发者开发而成。对于数据库访问、验证Web表单和用户身份认证等一系列功能,Flask框架是不支持的。这些功能都是以扩展组件的方式进行实现,然后再与Flask框架集成。开发者可以根据项目的需求进行相应的扩展,或者自行开发。这与大型框架恰恰相反,大型框架本身做出了大部分决定,难以灵活改变方案。

其他框架

Django的主要目的是简便、快速的开发数据库驱动的网站。它强调代码复用,多个组件可以很方便的以“插件”形式服务于整个框架,Django有许多功能强大的第三方插件,你甚至可以很方便的开发出自己的工具包。这使得Django具有很强的可扩展性。它还强调快速开发和DRY(Do Not Repeat Yourself)原则。

框架目录结构
默认配置

static和templates目录是默认配置,其中static用来存放静态资源,例如图片、js、css文件等。templates存放模板文件。
我们的网站逻辑基本在server.py文件中,当然,也可以给这个文件起其他的名字。

在这里插入图片描述

flask的目录包括以上这种框架,所谓static里就是放数据和渲染的文件,比如.csv,.txt,.css,.js,数据以及图片和视频。

templates,模板,就是HTML模板,放置HTML的地方。

app.py:flask运行的主程序

其他.py 蓝图,就是具备app.py的后端程序功能,但不是主程序,叫做蓝图

----app.py----


from flask import Flask, render_template
import news as news, products as products # 导入相应模块



app = Flask(__name__)  # 创建 Flask()对象: app



@app.route('/')  # 使用了蓝图,app.route() 这种模式就仍可以使用,注意路由重复的问题

def hello_world():  # 定义函数

    return render_template('index.html')




app.register_blueprint(news.new_list)  # 将news模块里的蓝图对象new_list注册到app

app.register_blueprint(products.product_list)  # 将products模块里的蓝图对象product_list注册到app

if __name__ == '__main__':

    app.run(host='127.0.0.1',port=8082, debug=True)  # 调试模式开 启动服务器 运行在默认的5000端口

-----蓝图------

  1. news(新闻界面蓝图)
from flask import Blueprint  # 导入Blueprint模块
from flask import Flask, render_template, request  # 导入相应模块
new_list = Blueprint('news', __name__)  # 创建一个blueprint对象。第一个参数可看做该blueprint对象的姓名



# 在一个app里,姓名不能与其余的Blueprint对象姓名重复

# 第二个参数__name__用作初始化

@new_list.route("/login", methods=['GET', 'POST'])  # 将蓝图对象当做‘app’那样使用

# def new():  # 定义函数news()
#


def login():  # 定义视图函数


        k = int(request.form.get('name'))
        b = int(request.form.get('password'))
        from pyecharts.charts import Line
        import pyecharts.options as opts
        import numpy as np
        x = np.linspace(0, 2 * np.pi, 100)
        y = k*x + b

        (Line(init_opts=opts.InitOpts(width="700px", height="300px"))
         .add_xaxis(xaxis_data=x)
         .add_yaxis(series_name="绘制线图", y_axis=y, label_opts=opts.LabelOpts(is_show=False))
         .set_global_opts(
            title_opts=opts.TitleOpts(title="我是标题", subtitle="我是副标题", title_link="https://www.baidu.com/"),
            tooltip_opts=opts.TooltipOpts(axis_pointer_type="cross"))
         ).render('templates/news.html')


        return render_template('news.html',**locals())

-----蓝图------
2. products(产品蓝图)

from flask import Blueprint  # 导入Blueprint模块
from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os
product_list = Blueprint('products', __name__)  # 创建一个blueprint对象。第一个参数可看做该blueprint对象的名字



# 在一个app里,对象名不能与其余的Blueprint对象名重复

# 第二个参数__name__用作初始化

@product_list.route("/products", methods=['POST', 'GET'])  # 将蓝图对象当做‘app’那样使用

def product():
    if request.method == 'POST':
        f = request.files['file']
        basepath = os.path.dirname(__file__)  # 当前文件所在路径
        upload_path = os.path.join(basepath, 'static/dataes',secure_filename(f.filename))  #注意:没有的文件夹一定要先创建,不然会提示没有该路径
        f.save(upload_path)

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    plt.switch_backend('agg')
    sns.set(style='whitegrid', context='notebook')  # style控制默认样式,context控制着默认的画幅大小
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
    df = pd.read_csv('static/dataes/kaggle.csv')  # 指你要用哪些列的数据
    df_corr=df.corr()
    sns.heatmap(df.corr(), annot=True, vmax=1, square=True, cmap="Blues")
    plt.savefig('static/images/heatmap.png')

    return render_template('products.html',**locals())



—templates(模板)—

index.html

 <!DOCTYPE html>

   <html lang="en">

   <head>

       <meta charset="UTF-8"><!--指定网页编码-->

       <title>Title</title><!--指定网页标题-->

   <style type="text/css">

    .div1 {

       height:180px;

       width:380px;

        border:1px solid #8A8989;

        margin:0 auto;

           }

   .input{

       display: block;

   	width: 350px;

   	height: 40px;

   	margin: 10px auto;

   }

    .button

   	{

        background: #2066C5;

   	color: white;

   	font-size: 18px;

   	font-weight: bold;

   	height: 50px;

   	border-radius: 4px;

   	}

       </style>

   </head><!--head区域完毕-->

   <body><!--body区域开始-->

   <h3 style="text-align:center">输入y=kx+b形式函数</h3>
   <div class="div1"><form action="login" method = "post"><!--定义表单开始-->

       <input type="number" class="input" name="name" placeholder="请输入回归系数"><!--输入文本框-->

   	<input type="number" class="input" name="password" placeholder="请输入回归截距"><!--输入文本框-->

       <input type="submit" value="输出"  class="input button" ><!--定义登陆用button-->

   </form></div> <!--form表单结束-->

   </body><!--body区域完毕-->

   </html>



news.html

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

</head>
<body>
    <div id="843fff3599974719a844a2289e4b73ff" class="chart-container" style="width:700px; height:300px;"></div>
    <script>
        var chart_843fff3599974719a844a2289e4b73ff = echarts.init(
            document.getElementById('843fff3599974719a844a2289e4b73ff'), 'white', {renderer: 'canvas'});
        var option_843fff3599974719a844a2289e4b73ff = {
    "animation": true,
    "animationThreshold": 2000,
    "animationDuration": 1000,
    "animationEasing": "cubicOut",
    "animationDelay": 0,
    "animationDurationUpdate": 300,
    "animationEasingUpdate": "cubicOut",
    "animationDelayUpdate": 0,
    "color": [
        "#c23531",
        "#2f4554",
        "#61a0a8",
        "#d48265",
        "#749f83",
        "#ca8622",
        "#bda29a",
        "#6e7074",
        "#546570",
        "#c4ccd3",
        "#f05b72",
        "#ef5b9c",
        "#f47920",
        "#905a3d",
        "#fab27b",
        "#2a5caa",
        "#444693",
        "#726930",
        "#b2d235",
        "#6d8346",
        "#ac6767",
        "#1d953f",
        "#6950a1",
        "#918597"
    ],
    "series": [
        {
            "type": "line",
            "name": "\u7ed8\u5236\u7ebf\u56fe",
            "connectNulls": false,
            "symbolSize": 4,
            "showSymbol": true,
            "smooth": false,
            "clip": true,
            "step": false,
            "data": [
                [
                    0.0,
                    65.0
                ],
                [
                    0.06346651825433926,
                    65.3173325912717
                ],
                [
                    0.12693303650867852,
                    65.63466518254339
                ],
                [
                    0.1903995547630178,
                    65.9519977738151
                ],
                [
                    0.25386607301735703,
                    66.26933036508679
                ],
                [
                    0.3173325912716963,
                    66.58666295635848
                ],
                [
                    0.3807991095260356,
                    66.90399554763017
                ],
                [
                    0.4442656277803748,
                    67.22132813890187
                ],
                [
                    0.5077321460347141,
                    67.53866073017358
                ],
                [
                    0.5711986642890533,
                    67.85599332144527
                ],
                [
                    0.6346651825433925,
                    68.17332591271696
                ],
                [
                    0.6981317007977318,
                    68.49065850398866
                ],
                [
                    0.7615982190520711,
                    68.80799109526035
                ],
                [
                    0.8250647373064104,
                    69.12532368653206
                ],
                [
                    0.8885312555607496,
                    69.44265627780375
                ],
                [
                    0.9519977738150889,
                    69.75998886907544
                ],
                [
                    1.0154642920694281,
                    70.07732146034714
                ],
                [
                    1.0789308103237674,
                    70.39465405161883
                ],
                [
                    1.1423973285781066,
                    70.71198664289054
                ],
                [
                    1.2058638468324459,
                    71.02931923416223
                ],
                [
                    1.269330365086785,
                    71.34665182543392
                ],
                [
                    1.3327968833411243,
                    71.66398441670562
                ],
                [
                    1.3962634015954636,
                    71.98131700797732
                ],
                [
                    1.4597299198498028,
                    72.29864959924902
                ],
                [
                    1.5231964381041423,
                    72.61598219052071
                ],
                [
                    1.5866629563584815,
                    72.9333147817924
                ],
                [
                    1.6501294746128208,
                    73.25064737306411
                ],
                [
                    1.71359599286716,
                    73.5679799643358
                ],
                [
                    1.7770625111214993,
                    73.8853125556075
                ],
                [
                    1.8405290293758385,
                    74.20264514687919
                ],
                [
                    1.9039955476301778,
                    74.51997773815089
                ],
                [
                    1.967462065884517,
                    74.83731032942259
                ],
                [
                    2.0309285841388562,
                    75.15464292069429
                ],
                [
                    2.0943951023931957,
                    75.47197551196598
                ],
                [
                    2.1578616206475347,
                    75.78930810323767
                ],
                [
                    2.221328138901874,
                    76.10664069450937
                ],
                [
                    2.284794657156213,
                    76.42397328578107
                ],
                [
                    2.3482611754105527,
                    76.74130587705277
                ],
                [
                    2.4117276936648917,
                    77.05863846832446
                ],
                [
                    2.475194211919231,
                    77.37597105959615
                ],
                [
                    2.53866073017357,
                    77.69330365086785
                ],
                [
                    2.6021272484279097,
                    78.01063624213955
                ],
                [
                    2.6655937666822487,
                    78.32796883341125
                ],
                [
                    2.729060284936588,
                    78.64530142468294
                ],
                [
                    2.792526803190927,
                    78.96263401595463
                ],
                [
                    2.8559933214452666,
                    79.27996660722633
                ],
                [
                    2.9194598396996057,
                    79.59729919849804
                ],
                [
                    2.982926357953945,
                    79.91463178976973
                ],
                [
                    3.0463928762082846,
                    80.23196438104142
                ],
                [
                    3.1098593944626236,
                    80.54929697231312
                ],
                [
                    3.173325912716963,
                    80.86662956358481
                ],
                [
                    3.236792430971302,
                    81.18396215485652
                ],
                [
                    3.3002589492256416,
                    81.50129474612821
                ],
                [
                    3.3637254674799806,
                    81.8186273373999
                ],
                [
                    3.42719198573432,
                    82.1359599286716
                ],
                [
                    3.490658503988659,
                    82.45329251994329
                ],
                [
                    3.5541250222429985,
                    82.770625111215
                ],
                [
                    3.6175915404973376,
                    83.08795770248669
                ],
                [
                    3.681058058751677,
                    83.40529029375838
                ],
                [
                    3.744524577006016,
                    83.72262288503008
                ],
                [
                    3.8079910952603555,
                    84.03995547630177
                ],
                [
                    3.8714576135146945,
                    84.35728806757348
                ],
                [
                    3.934924131769034,
                    84.67462065884517
                ],
                [
                    3.998390650023373,
                    84.99195325011686
                ],
                [
                    4.0618571682777125,
                    85.30928584138856
                ],
                [
                    4.1253236865320515,
                    85.62661843266025
                ],
                [
                    4.188790204786391,
                    85.94395102393196
                ],
                [
                    4.25225672304073,
                    86.26128361520365
                ],
                [
                    4.3157232412950695,
                    86.57861620647535
                ],
                [
                    4.3791897595494085,
                    86.89594879774704
                ],
                [
                    4.442656277803748,
                    87.21328138901875
                ],
                [
                    4.506122796058087,
                    87.53061398029044
                ],
                [
                    4.569589314312426,
                    87.84794657156213
                ],
                [
                    4.6330558325667655,
                    88.16527916283383
                ],
                [
                    4.696522350821105,
                    88.48261175410553
                ],
                [
                    4.759988869075444,
                    88.79994434537721
                ],
                [
                    4.823455387329783,
                    89.11727693664892
                ],
                [
                    4.886921905584122,
                    89.43460952792061
                ],
                [
                    4.950388423838462,
                    89.75194211919231
                ],
                [
                    5.013854942092801,
                    90.06927471046401
                ],
                [
                    5.07732146034714,
                    90.3866073017357
                ],
                [
                    5.14078797860148,
                    90.7039398930074
                ],
                [
                    5.204254496855819,
                    91.0212724842791
                ],
                [
                    5.267721015110158,
                    91.33860507555079
                ],
                [
                    5.331187533364497,
                    91.6559376668225
                ],
                [
                    5.394654051618837,
                    91.97327025809419
                ],
                [
                    5.458120569873176,
                    92.29060284936588
                ],
                [
                    5.521587088127515,
                    92.60793544063758
                ],
                [
                    5.585053606381854,
                    92.92526803190927
                ],
                [
                    5.648520124636194,
                    93.24260062318098
                ],
                [
                    5.711986642890533,
                    93.55993321445267
                ],
                [
                    5.775453161144872,
                    93.87726580572436
                ],
                [
                    5.838919679399211,
                    94.19459839699606
                ],
                [
                    5.902386197653551,
                    94.51193098826775
                ],
                [
                    5.96585271590789,
                    94.82926357953946
                ],
                [
                    6.029319234162229,
                    95.14659617081115
                ],
                [
                    6.092785752416569,
                    95.46392876208284
                ],
                [
                    6.156252270670908,
                    95.78126135335454
                ],
                [
                    6.219718788925247,
                    96.09859394462623
                ],
                [
                    6.283185307179586,
                    96.41592653589794
                ]
            ],
            "hoverAnimation": true,
            "label": {
                "show": false,
                "position": "top",
                "margin": 8
            },
            "lineStyle": {
                "show": true,
                "width": 1,
                "opacity": 1,
                "curveness": 0,
                "type": "solid"
            },
            "areaStyle": {
                "opacity": 0
            },
            "zlevel": 0,
            "z": 0
        }
    ],
    "legend": [
        {
            "data": [
                "\u7ed8\u5236\u7ebf\u56fe"
            ],
            "selected": {
                "\u7ed8\u5236\u7ebf\u56fe": true
            },
            "show": true,
            "padding": 5,
            "itemGap": 10,
            "itemWidth": 25,
            "itemHeight": 14
        }
    ],
    "tooltip": {
        "show": true,
        "trigger": "item",
        "triggerOn": "mousemove|click",
        "axisPointer": {
            "type": "cross"
        },
        "showContent": true,
        "alwaysShowContent": false,
        "showDelay": 0,
        "hideDelay": 100,
        "textStyle": {
            "fontSize": 14
        },
        "borderWidth": 0,
        "padding": 5
    },
    "xAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "gridIndex": 0,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "splitLine": {
                "show": false,
                "lineStyle": {
                    "show": true,
                    "width": 1,
                    "opacity": 1,
                    "curveness": 0,
                    "type": "solid"
                }
            },
            "data": null
        }
    ],
    "yAxis": [
        {
            "show": true,
            "scale": false,
            "nameLocation": "end",
            "nameGap": 15,
            "gridIndex": 0,
            "inverse": false,
            "offset": 0,
            "splitNumber": 5,
            "minInterval": 0,
            "splitLine": {
                "show": false,
                "lineStyle": {
                    "show": true,
                    "width": 1,
                    "opacity": 1,
                    "curveness": 0,
                    "type": "solid"
                }
            }
        }
    ],
    "title": [
        {
            "text": "\u6211\u662f\u6807\u9898",
            "link": "https://www.baidu.com/",
            "subtext": "\u6211\u662f\u526f\u6807\u9898",
            "padding": 5,
            "itemGap": 10
        }
    ]
};
        chart_843fff3599974719a844a2289e4b73ff.setOption(option_843fff3599974719a844a2289e4b73ff);
    </script>
</body>
</html>

products.html

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

</head>

<body>

    <h1>heatmap热力图显示以及计算</h1>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>

<img src="static/images/heatmap.png">
    <br>

{% for k,v in df_corr.items() %}
{{ v}}<br>
{% endfor %}
</body>

</html>

效果展示

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值