flask框架制作前端网页作为GUI

一、语法和原理

(一)、文件目录结构

需要注意的问题:启动文件命名必须是app.py

一个典型的Flask应用通常包含以下几个基本文件和文件夹:

app.py:应用的入口文件,包含了应用的初始化和配置。

requirements.txt:应用所依赖的Python包列表。可以使用该文件来管理应用的依赖关系。

README.md:应用的说明文档,包含了应用的运行方法、配置说明等。

venv/:虚拟环境文件夹,用于隔离应用的Python环境。

除了上述基本文件和文件夹外,应用的根目录还可以包含其他一些文件,例如:

static/:静态文件目录,用于存放应用所需的静态资源,如CSS样式表、JavaScript文件、图片等。

templates/:模板文件目录,用于存放应用的HTML模板文件。Flask使用Jinja2作为模板引擎,可以通过模板文件生成动态的HTML页面。

复制代码
app/
├── __init__.py
├── routes.py
├── models.py
├── forms.py
├── helpers.py
├── static/
│   ├── css/
│   ├── js/
│   └── images/
└── templates/
    └── base.html
    └── index.html
    └── ...

二、案例

(一)、目录结构如下:

(二)、功能与代码

读取文件到app文件夹下并将文件名写入对应的txt文件(现代浏览器不允许获取本地路径),后续通过读入txt的文件名来拼接路径,读取app文件夹下的文件。

步骤:

1、创建主页面

创建一个名为templates的目录,并在其中创建一个名为index.html的文件。将以下HTML代码粘贴到该文件中:

将url_for()函数指向的URL临时替换为了#。在实际项目中,请根据你的路由配置重新添加对应的URL路径。

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- 添加CSS样式 -->
    <style>
        /* 定义一个包含链接的容器,使其居中并分散布局 */
        .link-container {
            display: flex;
            justify-content: space-between; /* 使链接在容器内水平分散 */
            align-items: center; /* 使链接垂直居中 */
            width: 100%;
            max-width: 600px; /* 设置最大宽度以适应不同屏幕尺寸 */
            margin: 0 auto; /* 在页面中央对齐容器 */
            padding: 20px 0; /* 上下增加间距 */
        }

        /* 定义链接的基本样式 */
        .link-item {
            padding: 10px 15px; /* 内边距,提供点击区域 */
            border-radius: 4px; /* 圆角效果 */
            text-decoration: none; /* 去除默认下划线 */
            color: white; /* 文字颜色 */
            font-weight: bold; /* 加粗字体 */
            transition: background-color 0.3s ease; /* 添加平滑背景色过渡效果 */
        }

        /* 分别为三个链接设置不同的背景颜色 */
        .link-item.load-model {
            background-color: #e74c3c; /* 红色 */
        }

        .link-item.input-action {
            background-color: #2ecc71; /* 绿色 */
        }

        .link-item.output-action {
            background-color: #3498db; /* 蓝色 */
        }
    </style>

    <title>App Title</title>
</head>
<body>
    
    <!-- 创建一个包含三个链接的 Flexbox 容器 -->
    <div class="link-container">
        <!-- 第一个链接,指向 'load_model' 页面 -->
        <a href="#" class="link-item load-model">加载模型</a>
        
        <!-- 第二个链接,指向 'input' 页面 -->
        <a href="#" class="link-item input-action">输入</a>
        
        <!-- 第三个链接,指向 'output' 页面 -->
        <a href="#" class="link-item output-action">输出</a>
    </div>

    <!-- Jinja2 模板中的内容块(已移除 Flask 相关内容) -->
    <!-- {% block content %}{% endblock %} -->
</body>
</html>
2、创建二级页面

在二级页面中实现文件的上传功能。

在templates目录中创建三个子目录:load_model, input, 和 output。

在每个子目录中创建一个名为form.html的文件,并将以下HTML代码粘贴到每个文件中:

复制代码
<form method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">提交</button>
</form>
3、后端处理

通过Python路由函数实现数据的读取和文件名写入txt

更新的app.py以处理这些表单。将以下python代码添加到app.py文件中:

复制代码
from flask import Flask, render_template, request
import os

app = Flask(__name__)
model_file = 'model_name.txt'
input_file = 'input.txt'
output_file = 'output.txt'


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/load_model', methods=['GET', 'POST'])
def load_model():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = file.filename
            file.save(os.path.join(app.root_path, filename))
            print(f"模型已加载:{filename}")
            # 名称写入txt文档
            with open(model_file, 'w') as f:
                f.write(filename)
    return render_template('load_model/form.html')

@app.route('/input', methods=['GET', 'POST'])
def input():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = file.filename
            file.save(os.path.join(app.root_path, 'input'))
            print(f"输入文件已上传:{filename}")
            # 名称写入txt文档
            with open(model_file, 'w') as f:
                f.write(filename)
    return render_template('input/form.html')

@app.route('/output', methods=['GET', 'POST'])
def output():
    if request.method == 'POST':
        file = request.files['file']
        if file:
            filename = file.filename
            file.save(os.path.join(app.root_path, 'output'))
            print(f"输出文件已上传:{filename}")
    return render_template('output/form.html')

if __name__ == '__main__':
    app.run(debug=True)

运行python app.py时,应用程序将在http://localhost:5000上启动。您将看到一个包含三个按钮的页面,每个按钮都链接到一个表单,用于上传本地文件。点击每个按钮将打开一个新的页面,其中包含一个文件上传表单。提交表单后,文件将被保存到相应的目录中。

steamlit

需求

在上面的基础上做如下修改,1、上传按钮只留下一个,并取消上传文件大小限制。2、上传文件到E:\web_steamlit文件夹。3、输出部分为使用pandas 读取E:\web_steamlit文件夹下的 地址表.xlsx并在页面展示前10行,4、输出部分需要给出一个按钮让用户能从E:\web_steamlit下的 地址表.xlsx到用户指定位置

在generate_output()函数中,你尝试下载df变量,但df是一个Pandas DataFrame对象,不能直接下载。你需要将其转换为二进制数据,然后使用st.download_button()函数。你可以使用DataFrame.to_csv()方法将DataFrame转换为CSV文件,然后将其写入内存中。例如,你可以这样修改:

import os

import io

import pandas as pd

import streamlit as st

import streamlit.components.v1 as components

st.set_page_config(page_title="智能平台", page_icon=None, layout="centered", initial_sidebar_state="auto", menu_items=None)

设置主题

st.markdown(

f"""

""",

unsafe_allow_html=True

)

st.markdown("""
pass

""",unsafe_allow_html=True)

输入部分

def get_input(up_folder_path):

创建一个上传文件组件

file = st.file_uploader("输入文件")

检查是否上传了文件

if file is not None:

将文件保存到指定目录

file_path = up_folder_path+file.name

with open(file_path, 'wb') as f:

f.write(file.getvalue())

复制代码
return file

输出部分

def generate_output(file_path):

读取文件

df = pd.read_excel(file_path)

st.dataframe(df.head(10))

复制代码
# 创建一个下载按钮
csv_buffer = io.StringIO()
df.to_csv(csv_buffer, index=False)

# 将CSV文件内容转换为二进制数据
csv_data = csv_buffer.getvalue().encode("utf-8")

# 下载文件
st.download_button(
    "下载文件",
    csv_data,
    "result.csv",
    "text/csv"
)

主体部分

##https://www.zhihu.com/question/483788619/answer/3292315479 搜索 我们的Streamlit交流群中经常听到小伙伴们吐槽Streamlit自带的表格样式太不友好了

def draw_table(df, theme, table_height):

columns = df.columns

thead1=""""""

thead_temp = []

for k in range(len(list(columns))):

thead_temp.append(""""""+str(list(columns)[k])+"""""")

header = thead1+"".join(thead_temp)+""""""

rows = []

rows_temp = []

for i in range(df.shape[0]):

rows.append(""""""+str(i+1)+"""""")

rows_temp.append(df.iloc[i].values.tolist())

td_temp = []

for j in range(len(rows_temp)):

for m in range(len(rows_temp[j])):

td_temp.append(""""""+str(rows_temp[j][m])+"""""")

td_temp2 = []

for n in range(len(td_temp)):

td_temp2.append(td_temp[n:n+df.shape[1]])

td_temp3 = []

for x in range(len(td_temp2)):

if int(x % (df.shape[1])) == 0:

td_temp3.append(td_temp2[x])

td_temp4 = []

for xx in range(len(td_temp3)):

td_temp4.append("".join(td_temp3[xx]))

td_temp5 = []

for v in range(len(td_temp4)):

td_temp5.append(""""""+str(v+1)+""""""+str(td_temp4[v])+"""""")

table_html = """"""+

""""""+

"""<table class="table text-center table-bordered """+str(theme)+'"'+">""" +

header+""""""+"".join(td_temp5)+""""""

复制代码
return components.html(table_html,height=table_height, scrolling=True)

输出部分

def table_output(file_path):

读取文件

df = pd.read_excel(file_path)

theme_list=["bg-primary", "bg-success", "bg-warning", "bg-danger", "bg-info", "table-dark"]

theme = st.selectbox("请选择一种主题", theme_list)

draw_table(df, theme=theme, table_height=300)

显示前10行

st.dataframe(df.head(10))

def main():

#网页模型

st.title("智能平台")

复制代码
# 加载模型


# 获取用户输入
input_data = get_input(up_folder_path)

# 生成输出
generate_output(file_path)

#table_output(file_path)

if name == "main ":

file_path=r"E:\web_steamlit\地址表.xlsx"

up_folder_path=r"E:\web_steamlit\"

main()

相关推荐
用户69371750013842 小时前
Google 正在“收紧侧加载”:陌生 APK 安装或需等待 24 小时
android·前端
蓝帆傲亦2 小时前
Web 前端搜索文字高亮实现方法汇总
前端
用户69371750013842 小时前
Room 3.0:这次不是升级,是重来
android·前端·google
qq_417695053 小时前
机器学习与人工智能
jvm·数据库·python
漫随流水3 小时前
旅游推荐系统(view.py)
前端·数据库·python·旅游
yy我不解释4 小时前
关于comfyui的mmaudio音频生成插件时时间不一致问题(一)
python·ai作画·音视频·comfyui
踩着两条虫4 小时前
VTJ.PRO 核心架构全公开!从设计稿到代码,揭秘AI智能体如何“听懂人话”
前端·vue.js·ai编程
紫丁香5 小时前
AutoGen详解一
后端·python·flask
FreakStudio5 小时前
不用费劲编译ulab了!纯Mpy矩阵micronumpy库,单片机直接跑
python·嵌入式·边缘计算·电子diy
jzlhll1236 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin