导入
Streamlit Cloud
学习如何将我们的应用程序部署到 Streamlit Cloud。
部署选项
在完成应用程序的开发步骤后,现在是时候将其部署,以便用户可以与之交互。
有多种部署应用程序的方式,包括以下几种:
- Heroku
- AWS
- Streamlit Cloud
在本课程中,我们将学习如何使用 Streamlit Cloud 部署应用程序。
...
Streamlit Cloud 登录页面
Streamlit Cloud
连接服务
首次访问 Streamlit Cloud 时,会看到如上图所示的页面。
要将应用部署到 Streamlit Cloud,您需要一个 GitHub 账户,用于存放您的代码仓库(repo)。这是推荐的注册方式。
首次使用时,需完成将 GitHub 账户连接到该服务的过程。
仓库中应包含 Python 脚本文件以及一个 requirements.txt 文件,其中列出构建和运行应用程序所需的依赖包。
Streamlit Cloud 的社区版允许部署一个私有仓库和无限个公开仓库。
必需文件
作为演示,我们使用以下脚本部署一个基础的照片编辑器应用,该应用允许用户上传图片并进行基本操作:
1import streamlit as st 2import numpy as np 3from PIL import Image 4 5st.title("超基础照片编辑器") 6 7def display_figures(img1, img2): 8 fig1_left, fig2_right = st.columns(2) 9 with fig1_left: 10 st.markdown("### 原始图像") 11 st.image(img1) 12 with fig2_right: 13 st.markdown("### 处理后的图像") 14 st.image(img2) 15 16image_file = st.sidebar.file_uploader("上传图像文件", type=["jpg","png","tif"]) 17 18if image_file is not None: 19 input_image = Image.open(image_file) 20 21 effect = st.sidebar.selectbox("选择图像处理类型。", 22 ["旋转图像", "翻转图像", "调整大小"]) 23 24 if effect == "旋转图像": 25 angle = st.sidebar.select_slider("选择旋转角度", [0, 90, 180, 270, 360]) 26 output_image = input_image.rotate(angle) 27 28 if effect == "翻转图像": 29 mirror_choice = st.sidebar.radio("选择翻转方式", 30 ["水平翻转", "垂直翻转"]) 31 if mirror_choice == "水平翻转": 32 output_image = input_image.transpose(Image.FLIP_LEFT_RIGHT) 33 else: 34 output_image = input_image.transpose(Image.FLIP_TOP_BOTTOM) 35 36 if effect == "调整大小": 37 scale_factor = st.sidebar.slider("选择缩放比例", 5, 10, 6) 38 output_image = input_image.resize((input_image.width//scale_factor, input_image.height//scale_factor)) 39 40 if st.button("处理图像"): 41 display_figures(input_image, output_image)
我们需要创建一个 requirements.txt 文件,内容如下:
gitdb==4.0.7GitPython==3.1.17gunicorn==20.1.0Markdown==3.3.4streamlit==1.0.0pip==21.3
根据实际需求替换为合适的库版本。
...
用于部署的仓库准备就绪
部署应用程序
当仓库准备就绪后,进入您的 Streamlit Cloud 账户,点击“新建应用”按钮。
...
部署新应用的按钮
在弹出的新应用窗口中,指定项目的仓库和脚本文件。
...
指定仓库信息
如果应用运行需要访问凭证(如 API 密钥),需通过 toml 格式的配置文件传入。这可以在部署页面的“高级设置”选项卡中完成。
...
用于传递凭证的应用配置
所有配置完成后,点击“部署”,系统将开始构建项目。
...
部署过程中应用构建完成
部署成功后,即可从任意位置访问该应用。