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

相关推荐
紫雾凌寒1 小时前
计算机视觉 |解锁视频理解三剑客——TimeSformer
python·深度学习·神经网络·计算机视觉·transformer·timesformer
程序员杰哥2 小时前
测试用例详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
go54631584657 小时前
本地部署 GitHub 上的 Python 人脸识别项目
开发语言·python·github
FreakStudio8 小时前
手把手教你用 MicroPython 玩转幻尔串口舵机,代码+教程全公开
python·嵌入式·大学生·面向对象·技术栈·电子diy·电子计算机
tekin8 小时前
基于 Python 开发在线多人游戏服务器案例解析
服务器·python·游戏·在线多人游戏服务器
让学习成为一种生活方式10 小时前
libGL.so.1: cannot open shared object file: No such file or directory-linux022
linux·开发语言·python
java1234_小锋11 小时前
一周学会Flask3 Python Web开发-Jinja2模板继承和include标签使用
python·flask·flask3
图书馆钉子户11 小时前
from flask_session import Session 为什么是Session(app)这么用?
python·flask·mybatis
一只蜗牛儿11 小时前
Sherpa-ONNX:说话人识别与语音识别自动开启(VAD)+ Python API 完整指南
人工智能·python·语音识别
结衣结衣.11 小时前
【OpenCV】入门教学
图像处理·人工智能·python·opencv