推荐一个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

相关推荐
无垠的广袤8 分钟前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:缺陷检测
linux·人工智能·python·opencv·开发板
Duang007_9 分钟前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
浒畔居1 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
抠头专注python环境配置1 小时前
基于Pytorch ResNet50 的珍稀野生动物识别系统(Python源码 + PyQt5 + 数据集)
pytorch·python
百***78751 小时前
Kimi K2.5开源模型实战指南:核心能力拆解+一步API接入(Python版,避坑全覆盖)
python·microsoft·开源
喵手1 小时前
Python爬虫实战:针对天文历法网站(以 TimeandDate 或类似的静态历法页为例),构建高精度二十四节气天文数据采集器(附xlsx导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集天文历法网站数据·构建二十四节气天文数据
zhaotiannuo_19982 小时前
Python之2.7.9-3.9.1-3.14.2共存
开发语言·python
Keep_Trying_Go2 小时前
基于GAN的文生图算法详解ControlGAN(Controllable Text-to-Image Generation)
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·文生图
LostSpeed2 小时前
openpnp - python2.7 script - 中文显示乱码,只能显示英文
python·openpnp
hhy_smile2 小时前
Class in Python
java·前端·python