Python Flask案例:制作一个数据分析网站

来自CloudWiki
跳转至: 导航搜索

上传数据

python

from flask import Flask
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from werkzeug.utils import secure_filename
import os 
app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称
app.config['UPLOAD_FOLDER'] = "upload_files/"


#允许的扩展名
ALLOWED_EXTENSIONS = set(['xls','xlsx','csv'])


#检验文件后缀名是否合法
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

# 上传数据文件
@app.route('/data', methods=['GET', 'POST'])
def do_data():

    if request.method == 'GET': # 如果展示表单
        return render_template('data.html')
    elif request.method == 'POST':#如果是提交表单
        # 从表单中获取字段
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)#导入Werkzeug提供的secure_filename()函数来检查文件名
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return render_template('data.html', info="上传成功!")       
        else:
            return render_template('data.html', info="文件类型错误!") 


if __name__ == '__main__':#程序入口
    #app.run()#让应用运行在本地服务器上。
    app.secret_key='secret123'
    app.run(host='0.0.0.0',port="5006",debug="true") #允许任意网址访问本站

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="content">
  <h1 class="title-center">数据导入</h1>
  <div  style="color:red;">{{info}}</div>
  <form action="" method="POST"  enctype="multipart/form-data">

    <div class="form-group">
       <input type="file" name="file">
    </div>

    <button type="submit" class="btn btn-primary">提交</button>
  </form>
</div>

<script>

</script>
</body>
</html>

效果图

Python2023013002.png

本地分析数据

数据来源:https://static.runoob.com/download/nba.csv

import pandas as pd

df = pd.read_csv('nba.csv')

#print(df)
#print(df.info())
#print(df.head(10))
#print(df.tail(15))
'''
for index,row in df.iterrows():
    
    print(index,row['Name'],row['Age'],row['Weight'])
'''
#简单统计
print(df['Age'].max())
print(df['Age'].min())
print(df['Age'].mean())
print(df['Age'].std())
print(df['Age'].describe())

输出:

40.0
19.0
26.938730853391686
4.404016424405833
count    457.000000
mean      26.938731
std        4.404016
min       19.000000
25%       24.000000
50%       26.000000
75%       30.000000
max       40.000000
Name: Age, dtype: float64

线上分析数据

html

from flask import Flask
from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
from werkzeug.utils import secure_filename
import os 
app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称
app.config['UPLOAD_FOLDER'] = "upload_files/"


#允许的扩展名
ALLOWED_EXTENSIONS = set(['xls','xlsx','csv'])


#检验文件后缀名是否合法
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def pandas_analysis(filename):
    import pandas as pd

    df = pd.read_csv(filename)

    #print(df)
    #print(df.info())
    #print(df.head(10))
    #print(df.tail(15))
    '''
    for index,row in df.iterrows():
        
        print(index,row['Name'],row['Age'],row['Weight'])
    '''
    #简单统计
    #print(df['Age'].max())
    #print(df['Age'].min())
    #print(df['Age'].mean())
    #print(df['Age'].std())
    #print(df['Age'].describe())
    #result = str(df['Age'].describe())
    result=df.describe()
    return result
    
# 上传数据文件
@app.route('/data', methods=['GET', 'POST'])
def do_data():

    if request.method == 'GET': # 如果展示表单
        return render_template('data.html')
    elif request.method == 'POST':#如果是提交表单
        # 从表单中获取字段
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)#导入Werkzeug提供的secure_filename()函数来检查文件名
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            result = pandas_analysis(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #result = pandas_analysis("upload_files/nba.csv")
            return render_template('data.html', info="上传成功!",result=result)       
        else:
            return render_template('data.html', info="文件类型错误!") 


if __name__ == '__main__':#程序入口
    #app.run()#让应用运行在本地服务器上。
    app.secret_key='secret123'
    app.run(host='0.0.0.0',port="5006",debug="true") #允许任意网址访问本站

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div class="content">
  <h1 class="title-center">数据导入</h1>
  <div  style="color:red;">{{info}}</div>
  <form action="" method="POST"  enctype="multipart/form-data">

    <div class="form-group">
       <input type="file" name="file">
    </div>

    <button type="submit" class="btn btn-primary">提交</button>
  </form>
</div>
<div style="color:blue">
    该数据的数据分析为:
</div>
<div style="color:blue">
   {{result}}
</div>
<script>

</script>
</body>
</html>



效果图

Python2023020202.png