推荐一个Python的前端框架Streamlit

WHY,为什么要用Streamlit

你是不是也想写一个简单的前端界面做些简单的展示和控制,不想写html、css、js,也用不到前后端分离,用不到特别复杂的Flask、Django等,如果你遇到类似这样的问题,我推荐你试试Streamlit。

Streamlit介绍

官网链接: https://streamlit.io/
官方文档: https://docs.streamlit.io/ 推荐多查看这个资料

A faster way to build and share data apps,Streamlit turns data scripts into shareable web apps in minutes. All in pure Python. No front‑end experience required.

更快地构建和共享数据应用程序Streamlit在几分钟内将数据脚本转换为可共享的web应用程序。 都是用纯Python编写的。不需要前端经验。

实际使用下来和官方介绍所说的一样,使用Streamlit可以快速搭建一个前端展示页面,并很方便的部署在服务器上。看几个样例:

文本的展示:

类似GPT的对话app:

安装

**注意:**对python版本有要求,需要python的版本在3.8以上,已测试3.8以下的版本无法运行。

step1: 建议创建一个虚拟环境

shell 复制代码
cd myproject
python -m venv .venv

step2: 激活这个环境

shell 复制代码
# Windows command prompt
.venv\Scripts\activate.bat

# Windows PowerShell
.venv\Scripts\Activate.ps1

# macOS and Linux
source .venv/bin/activate

step3:安装streamlit

shelll 复制代码
pip install streamlit

#测试安装是否成功,执行下面命令,如果安装成功会打开浏览器弹出测试app
streamlit hello

安装成功

快速上手

创建一个app

1.创建一个python文件如:app.py

为了方便,我们使用了这种方式:import streamlit as st 导入Streamlit,后续直接用st进行调用即可。

2.给app创建个title

python 复制代码
st.title('Hello Streamlit')

3.运行这个app

shell 复制代码
streamlit run app.py

完成启动,后续的代码改动,直接生效,不需要再重新启动。

  1. 添加一些常见的元素
python 复制代码
import streamlit as st

st.title('Hello Streamlit')

st.text_input('What is your name?')
st.button('Click here', type='primary')
st.slider(label='progress', min_value=0, max_value=100, step=1,value=20)

st.write('下面是一段markdown文本')
'''
## markdown耳机标题
正文内容
'''

可以看到这里直接用markdown的格式写内容。

其他示例项目

https://gw-quickview.streamlit.app/

https://prettymapp.streamlit.app/

https://mito-for-st-demo.streamlit.app/

进阶使用

布局

streamlit提供了container和columns的概念进行页面的划分和布局。在页面可以插入一个container,也可以分成几个column,这两者可以互相嵌套进行布局。

python 复制代码
#数组里的数字,是将三列按照不同的比例进行了划分,第一列占了50%
c1,c2,c3 = st.columns([3, 2, 1])

官方示例:

缓存和状态

每次页面加载都会全局重新拉取数据了,如果有的数据特别大,体验就不太好,所以这里使用缓存可以避免每次都从接口请求加载。state可以用来控制一个状态的变量,这变量的变化,可以刷新到所有使用到的地方。
https://docs.streamlit.io/develop/api-reference/caching-and-state

缓存

缓存使用参考:

python 复制代码
import streamlit as st

@st.cache_data
def fetch_and_clean_data(url):
    # Fetch data from URL here, and then clean it up.
    return data

d1 = fetch_and_clean_data(DATA_URL_1)
# Actually executes the function, since this is the first time it was
# encountered.

d2 = fetch_and_clean_data(DATA_URL_1)
# Does not execute the function. Instead, returns its previously computed
# value. This means that now the data in d1 is the same as in d2.

d3 = fetch_and_clean_data(DATA_URL_2)
# This is a different URL, so the function executes.

缓存数据持久化的方式,可以选择持久化到硬盘。

python 复制代码
import streamlit as st

@st.cache_data(persist="disk")
def fetch_and_clean_data(url):
    # Fetch data from URL here, and then clean it up.
    return data
状态

状态的使用参考:

python 复制代码
# Initialization
if 'key' not in st.session_state:
    st.session_state['key'] = 'value'

# Session State also supports attribute based syntax
if 'key' not in st.session_state:
    st.session_state.key = 'value'

读取和更新state:

python 复制代码
# Read
st.write(st.session_state.key)

st.session_state.key = 'value2'     # Attribute API
st.session_state['key'] = 'value2'  # Dictionary like API
获取和修改url中的参数
python 复制代码
# You can read query params using key notation
if st.query_params["first_key"] == "1":
    do_something()

# ...or using attribute notation
if st.query_params.second_key == "two":
    do_something_else()

# And you can change a param by just writing to it
st.query_params.first_key = 2  # This gets converted to str automatically

点击按钮触发函数

python 复制代码
if st.button('Click here', type='primary'):
    st.write('点击了按钮')

弹窗

python 复制代码
# 弹窗定义个函数,加上这个注解就可以了
@st.experimental_dialog("弹窗示例")
def alert_dialog():
    st.write('弹窗内容')
    if st.button('确认', key='ok'):
        st.rerun()
    if st.button('取消', key='cancel'):
        st.rerun()


if st.button("点击弹窗"):
    alert_dialog()

总结

这里介绍了常见的一些用法,更多使用参考官方文档:https://docs.streamlit.io/develop/api-reference

相关推荐
waterHBO23 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七1 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate3 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼3 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio5 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
redcocal7 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
artificiali7 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
RaidenQ7 小时前
2024.9.13 Python与图像处理新国大EE5731课程大作业,索贝尔算子计算边缘,高斯核模糊边缘,Haar小波计算边缘
图像处理·python·算法·课程设计
花生了什么树~.8 小时前
python基础知识(六)--字典遍历、公共运算符、公共方法、函数、变量分类、参数分类、拆包、引用
开发语言·python
Trouvaille ~8 小时前
【Python篇】深度探索NumPy(下篇):从科学计算到机器学习的高效实战技巧
图像处理·python·机器学习·numpy·信号处理·时间序列分析·科学计算