用纯python写web app:Streamlit

简介: 一句话,Streamlit是一个可以用python编写web app的库,可以方便的动态展示你的机器学习的项目。【2月更文挑战第9天】

用纯python写web app:Streamlit

1. Streamlit

一句话,Streamlit是一个可以用python编写web app的库,可以方便的动态展示你的机器学习的项目。

优点

  • 你不需要懂html, css, js等,纯python语言编写web app
  • 包括web常用组件:文本框, 按钮,单选框,复选框, 下拉框,多媒体(图片,视频)和文件上传等

应用场景

  • 可以动态的探索数据
  • 可以方便动态展示你的机器学习成果(可以和jupyter notebook做个比较)

https://github.com/streamlit/streamlit

2. 安装

pip install streamlit
streamlit hello

# 启动web app
# streamlit run [filename]
streamlit run app.py

# You can now view your Streamlit app in your browser.
# Local URL: http://localhost:8501

3. 基本组件介绍

3.1 布局

web中通常有布局layout css, 如Bootstrap中的12列删格系统;streamlit最多只有左右两栏,通常是一栏。 通过st.sidebar添加侧边栏,通常可作为菜单,选择控制操作。在上下结构上,streamlit按照代码顺序从上到下,依次布局

import streamlit as st
import numpy as np
import time
import pandas as pd
import datetime
# 侧边栏
st.sidebar.title('菜单侧边栏')
add_selectbox = st.sidebar.selectbox(
    "这个是下拉框,请选择?",
    ("1", "Home 2", "Mobile 2")
)
# 主栏
st.title('Steamlit 机器学习web app')

3.2 text

streamlit提供了许多文本显示命令,还支持markdown语法


st.header('1. text文本显示')
st.markdown('Streamlit is **_really_ cool**.')
st.text('This is some text.')
st.subheader('This is a subheader')
st.write("st.write 可以写很多东西哦")
st.warning('This is a warning')

3.3 表单控件

streamlit提供丰富的表单控件,如按钮,单选框,复选框,下拉框,文本框和文件上传。
用法提炼如下:

  • 函数调用为定义显示控件,返回值是表示是否触发,或者触发返回结果;比如按钮,st.button('Say hello')定义了一个按钮, 如果按下按钮返回True,否则为False

st.markdown('- 按钮')
if st.button('Say hello'):
    st.write('Why hello there')

st.markdown('- 单选框')
genre = st.radio(
     "选择你喜欢的?",
    ('Comedy', 'Drama', 'Documentary'))

st.write('你选择了:', genre)


st.markdown('- 复选框')    
agree = st.checkbox('I agree')
if agree:
    st.write('感谢你同意了')



st.markdown('- 下拉框') 
option = st.selectbox(
    '你喜欢的联系方式?',
   ('Email', 'Home phone', 'Mobile phone'))

st.write('你选择了:', option)

st.markdown('- 多选下拉框') 
options = st.multiselect(
    'What are your favorite colors',
    ['Green', 'Yellow', 'Red', 'Blue'],
    ['Yellow', 'Red'])

st.write('你选择了:', options)

st.markdown('- slider') 
values = st.slider(
    'Select a range of values',
    0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)


st.markdown('- 文本输入') 
title = st.text_input('Movie title', 'Life of Brian')
st.write('The current movie title is', title)

txt = st.text_area('Text to analyze', '''
    It was the best of times, it was the worst of times, it was
    the age of wisdom, it was the age of foolishness, it was
    the epoch of belief, it was the epoch of incredulity, it
    was the season of Light, it was the season of Darkness, it
    was the spring of hope, it was the winter of despair, (...)
    ''')


st.markdown('- 日期与时间')
d = st.date_input(
    "生日",
    datetime.date(2019, 7, 6))
st.write('Your birthday is:', d)

t = st.time_input('闹钟', datetime.time(8, 45))
st.write('闹钟为:', t)

st.markdown('- 上传文件')
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)

3.4 图像

常用的图像库都支持,通过st.image展示图片

import cv2
img = cv2.imread('sunrise.jpg')
st.image(img[...,::-1], caption='Sunrise by the mountains',
        use_column_width=True)

3.5 图表

  • 支持pandas中的dataframe展示图表(折线图,面积图和柱状图)
    st.subheader('4.1 dataframe图表')
    @st.cache(persist=True)
    def get_data():
      df = pd.DataFrame(
      np.random.randn(200, 3),
      columns=['a', 'b', 'c'])
      return df
    df = get_data()
    # st.table(df)
    st.dataframe(df) 
    st.line_chart(df)
    st.area_chart(df)
    st.bar_chart(df)
    
  • 还支持matplotlib的图表展示,这个你应该很熟悉
    plt.plot(df.a, df.b)
    st.pyplot()
    

3.6 缓存

streamlit中数据的缓存使用st.cache装饰器来修饰, 注意是作用于函数。缓存的好处顾名思义就是避免每次刷新的时候都要重新加载数据。

@st.cache(persist=True)
def get_data():
    df = pd.DataFrame(
    np.random.randn(200, 3),
    columns=['a', 'b', 'c'])
    return df

4. 动态数据demo

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# 侧边栏
st.sidebar.title('请选择过滤条件')
time = st.sidebar.time_input('大于时间', datetime.time(1, 0))

values = st.sidebar.slider(
    '速度',
    0.0, 200.0, (25.0, 75.0))
# 主栏
st.title('数据探索')
@st.cache(persist=True)
def get_data():
    file = './7000.csv'
    return pd.read_csv(file, header=0)
data = get_data()
# print(values)
display_data = data[data['time'] > str(time)]
display_data = display_data[(display_data['速度'] > values[0]) & (display_data['速度'] < values[1])]
st.line_chart(display_data[['方向', '速度']])

5. 机器视觉项目demo

这个例子我们用人脸检测来说明下机器视觉项目的展示。

  • 功能:上传一张图片,检测出人脸框
  • 人脸检测算法来自facenet项目https://github.com/davidsandberg/facenet/tree/master/src/align中的MTCNN算法
  • 布局为左右布局,左边为上传空间, 右边是展示
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import time
import pandas as pd
import datetime
import cv2
from PIL import Image
import io
from face_detect.mtcnn_tf import MTCNN

# 侧边栏
st.sidebar.title('请上传一张照片,开始检测')
uploaded_file = st.sidebar.file_uploader("", type="jpg")

# 主栏
st.title('人脸检测')
@st.cache()
def init_model():
    mtcnn = MTCNN()
    return mtcnn

detect = init_model()
if uploaded_file is not None:
    # print(uploaded_file)
    data = np.array(Image.open(io.BytesIO(uploaded_file.read())))
    _, bboxs, _, _ = detect.run(data, detect_multiple_faces=True, margin=0)
    # display bbox and landmarks
    for idx, landmark in enumerate(landmarks):
        bbox = bboxs[idx]
        cv2.rectangle(data, (bbox[1], bbox[0]),
                      (bbox[3], bbox[2]), (0, 2255, 0), 2)
    st.image(data, caption='image', use_column_width=False)

6. 总结

是不是觉得很方便,分分钟就可以构建一个web app来展示你的项目。希望对你有帮助, 快动起手来吧!
摘要如下:

  • 数据记得要用缓存@st.cache()
  • streamlit可以支持matplotlib
  • streamlit有漂亮的表单控件,函数的返回值就是触发的值
  • streamlit支持markdown

官方提供了其他复杂的demo(官方推荐用函数的方式的封装业务,这里也推荐, 本文主要是为了说明功能,采用比较直观的方式来编写)

目录
相关文章
|
2天前
|
JavaScript 前端开发 Android开发
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
34 13
【03】仿站技术之python技术,看完学会再也不用去购买收费工具了-修改整体页面做好安卓下载发给客户-并且开始提交网站公安备案-作为APP下载落地页文娱产品一定要备案-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
3月前
|
安全 关系型数据库 测试技术
学习Python Web开发的安全测试需要具备哪些知识?
学习Python Web开发的安全测试需要具备哪些知识?
121 61
|
3月前
|
存储 监控 安全
如何在Python Web开发中确保应用的安全性?
如何在Python Web开发中确保应用的安全性?
|
3月前
|
安全 测试技术 网络安全
如何在Python Web开发中进行安全测试?
如何在Python Web开发中进行安全测试?
|
4天前
|
JavaScript 搜索推荐 Android开发
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
23 8
【01】仿站技术之python技术,看完学会再也不用去购买收费工具了-用python扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-客户的麻将软件需要下载落地页并且要做搜索引擎推广-本文用python语言快速开发爬取落地页下载-优雅草卓伊凡
|
4天前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
29 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
1天前
|
数据采集 Web App开发 存储
打造高效的Web Scraper:Python与Selenium的完美结合
本文介绍如何使用Python结合Selenium,通过代理IP、设置Cookie和User-Agent抓取BOSS直聘的招聘信息,包括公司名称、岗位、要求和薪资。这些数据可用于行业趋势、人才需求、企业动态及区域经济分析,为求职者、企业和分析师提供宝贵信息。文中详细说明了环境准备、代理配置、登录操作及数据抓取步骤,并提醒注意反爬虫机制和验证码处理等问题。
打造高效的Web Scraper:Python与Selenium的完美结合
|
2月前
|
机器学习/深度学习 人工智能 数据处理
[python 技巧] 快速掌握Streamlit: python快速原型开发工具
本文旨在快速上手python的streamlit库,包括安装,输入数据,绘制图表,基础控件,进度条,免费部署。
385 64
[python 技巧] 快速掌握Streamlit: python快速原型开发工具
|
1月前
|
JSON 安全 中间件
Python Web 框架 FastAPI
FastAPI 是一个现代的 Python Web 框架,专为快速构建 API 和在线应用而设计。它凭借速度、简单性和开发人员友好的特性迅速走红。FastAPI 支持自动文档生成、类型提示、数据验证、异步操作和依赖注入等功能,极大提升了开发效率并减少了错误。安装简单,使用 pip 安装 FastAPI 和 uvicorn 即可开始开发。其优点包括高性能、自动数据验证和身份验证支持,但也存在学习曲线和社区资源相对较少的缺点。
84 15
|
3月前
|
监控 安全 测试技术
如何在实际项目中应用Python Web开发的安全测试知识?
如何在实际项目中应用Python Web开发的安全测试知识?
118 61

热门文章

最新文章

  • 1
    打造高效的Web Scraper:Python与Selenium的完美结合
    13
  • 2
    Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
    26
  • 3
    AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
    20
  • 4
    【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
    54
  • 5
    部署使用 CHAT-NEXT-WEB 基于 Deepseek
    342
  • 6
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    26
  • 7
    java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
    40
  • 8
    零基础构建开源项目OpenIM桌面应用和pc web- Electron篇
    28
  • 9
    【01】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-硬件设备实时监控系统运营版发布-本产品基于企业级开源项目Zabbix深度二开-分步骤实现预计10篇合集-自营版
    22
  • 10
    FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
    55
  • 推荐镜像

    更多