Streamlit 开源项目教程
1. 项目的目录结构及介绍
Streamlit 项目的目录结构如下:
streamlit/
├── .github/
├── bin/
├── lib/
├── scripts/
├── streamlit/
│ ├── __init__.py
│ ├── annotations/
│ ├── bootstrap/
│ ├── caching/
│ ├── cli/
│ ├── config.py
│ ├── credentials.py
│ ├── delta_generator.py
│ ├── deprecation.py
│ ├── elements/
│ ├── errors.py
│ ├── file_util.py
│ ├── hello.py
│ ├── image_util.py
│ ├── legacy_caching/
│ ├── log_handler.py
│ ├── media_file_manager.py
│ ├── metrics_util.py
│ ├── net_util.py
│ ├── report.py
│ ├── report_thread.py
│ ├── secrets.py
│ ├── session_data.py
│ ├── session_state.py
│ ├── source_util.py
│ ├── spinner.py
│ ├── status.py
│ ├── string_util.py
│ ├── temp_deploy_server.py
│ ├── testing/
│ ├── type_util.py
│ ├── url_util.py
│ ├── util.py
│ ├── vendor/
│ ├── version.py
│ ├── v1/
│ ├── v2/
│ ├── v3/
│ ├── watcher/
│ └── widgets/
├── tests/
├── .gitignore
├── .pre-commit-config.yaml
├── .readthedocs.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── MANIFEST.in
├── README.md
├── RELEASE_PROCESS.md
├── SECURITY.md
├── setup.cfg
├── setup.py
├── streamlit.requirements.txt
└── tox.ini
主要目录和文件介绍:
- .github/: GitHub 配置文件,包括 issue 模板、PR 模板等。
- bin/: 包含可执行脚本。
- lib/: 包含一些库文件。
- scripts/: 包含一些辅助脚本。
- streamlit/: 核心代码目录,包含 Streamlit 的主要功能实现。
- config.py: 配置文件处理。
- credentials.py: 凭证管理。
- hello.py: 示例应用。
- secrets.py: 密钥管理。
- util.py: 通用工具函数。
- tests/: 测试代码目录。
- .gitignore: Git 忽略文件配置。
- LICENSE: 开源许可证。
- README.md: 项目说明文档。
- setup.py: 安装脚本。
2. 项目的启动文件介绍
Streamlit 的启动文件是 streamlit/hello.py
,这是一个示例应用,展示了如何使用 Streamlit 构建一个简单的 Web 应用。
hello.py
文件内容:
import streamlit as st
x = st.slider("Select a value")
st.write(x, "squared is", x * x)
启动命令:
streamlit run streamlit/hello.py
3. 项目的配置文件介绍
Streamlit 的配置文件主要包括 config.py
和 secrets.py
。
config.py
文件介绍:
config.py
文件负责处理 Streamlit 的配置选项,包括从命令行参数、环境变量和配置文件中读取配置。
secrets.py
文件介绍:
secrets.py
文件用于管理敏感信息,如 API 密钥、数据库密码等。这些信息通常不会被提交到版本控制系统中。
配置示例:
在项目根目录下创建一个 .streamlit/secrets.toml
文件,内容如下:
# .streamlit/secrets.toml
[database]
username = "your_username"
password = "your_password"
然后在代码中使用:
import streamlit as st