提示
本页面仅包含st.connection API。要深入了解在Streamlit应用程序中创建和管理数据连接,请阅读连接到数据。
创建一个到数据存储或API的新连接,或返回一个现有的连接。
连接的配置选项、凭证和密钥来自以下来源:
- 传递给此命令的关键字参数。
- 应用程序的 secrets.toml 文件。
- 任何特定于连接的配置文件。
从st.connection返回的连接在内部使用st.cache_resource进行缓存,因此在不同会话之间共享。
| 函数签名[source] | |
|---|---|
st.connection(name, type=None, max_entries=None, ttl=None, **kwargs) | |
| 参数 | |
name (str) | 用于在secrets.toml中查找机密的连接名称。
Streamlit 使用[connections. |
type (str, connection class, or None) | 要创建的连接类型。可以是以下之一:
|
max_entries (int or None) | 缓存中保留的最大连接数。 如果这是None(默认值),则缓存是无限制的。否则,当 新条目添加到已满的缓存时,最旧的缓存条目将被移除。 |
ttl (float, timedelta, or None) | 缓存中保留结果的最大秒数。 如果这是None(默认值),缓存的结果不会随时间过期。 |
**kwargs (any) | 传递给连接的._connect()方法的特定连接关键字参数。**kwargs通常与secrets.toml中的键值对结合使用(并优先于它们)。要了解更多信息,请参阅特定连接的文档。 |
| 返回 | |
(BaseConnection的子类) | 指定type的初始化连接对象。 |
示例
示例 1:推断的连接类型
创建第一方(SQL、Snowflake 或 Snowpark)连接的最简单方法是使用它们的默认名称,并在您的 secrets.toml 文件中定义相应的部分。以下示例创建了一个 "sql" 类型的连接。
.streamlit/secrets.toml:
[connections.sql] dialect = "xxx" host = "xxx" username = "xxx" password = "xxx"您的应用程序代码:
import streamlit as st conn = st.connection("sql")示例2:命名连接
创建具有自定义名称的连接需要您明确指定类型。如果type没有作为关键字参数传递,则必须在secrets.toml的适当部分中设置。以下示例创建了两个"sql"类型的连接,每个连接都有自己的自定义名称。第一个在st.connection命令中定义了type;第二个在secrets.toml中定义了type。
.streamlit/secrets.toml:
[connections.first_connection] dialect = "xxx" host = "xxx" username = "xxx" password = "xxx" [connections.second_connection] type = "sql" dialect = "yyy" host = "yyy" username = "yyy" password = "yyy"您的应用程序代码:
import streamlit as st conn1 = st.connection("first_connection", type="sql") conn2 = st.connection("second_connection")示例3:使用连接类的路径
将完整的模块路径传递给连接类可能很有用,尤其是在使用自定义连接时。虽然这不是创建第一方连接的典型方式,但以下示例创建了与type="sql"相同类型的连接。请注意,type是一个字符串路径。
.streamlit/secrets.toml:
[connections.my_sql_connection] url = "xxx+xxx://xxx:xxx@xxx:xxx/xxx"您的应用程序代码:
import streamlit as st conn = st.connection( "my_sql_connection", type="streamlit.connections.SQLConnection" )示例 4:导入连接类
您可以直接将连接类传递给st.connection命令。这样做可以让静态类型检查工具如mypy推断出st.connection的确切返回类型。以下示例创建了与示例3中相同的连接。
.streamlit/secrets.toml:
[connections.my_sql_connection] url = "xxx+xxx://xxx:xxx@xxx:xxx/xxx"您的应用程序代码:
import streamlit as st from streamlit.connections import SQLConnection conn = st.connection("my_sql_connection", type=SQLConnection)
要全面了解此功能,请查看Streamlit开发者体验产品经理Joshua Carroll的视频教程。您将通过实际示例了解该功能在创建和管理应用程序内数据连接中的实用性。
还有问题吗?
我们的 论坛 充满了有用的信息和Streamlit专家。