Connect Streamlit to MongoDB

本指南解释了如何从Streamlit社区云安全地访问远程MongoDB数据库。它使用了PyMongo库和Streamlit的Secrets管理

push_pin

注意

如果您已经有一个想要使用的数据库,请随时跳到下一步

首先,按照官方教程安装MongoDB设置认证(记下用户名和密码!),并连接到MongoDB实例。连接成功后,打开mongo shell并输入以下两个命令以创建一个包含一些示例值的集合:

use mydb db.mycollection.insertMany([{"name" : "Mary", "pet": "dog"}, {"name" : "John", "pet": "cat"}, {"name" : "Robert", "pet": "bird"}])

您的本地 Streamlit 应用程序将从应用程序根目录中的文件 .streamlit/secrets.toml 读取密钥。如果该文件尚不存在,请创建此文件并添加数据库信息,如下所示:

# .streamlit/secrets.toml [mongo] host = "localhost" port = 27017 username = "xxx" password = "xxx"
priority_high

重要

将您的应用密钥复制到Streamlit Community Cloud时,请确保将hostportusernamepassword的值替换为您的远程 MongoDB数据库的值!

将此文件添加到.gitignore中,不要将其提交到你的GitHub仓库!

由于上面的secrets.toml文件没有提交到GitHub,你需要将其内容单独传递给你部署的应用程序(在Streamlit社区云上)。转到应用程序仪表板,在应用程序的下拉菜单中,点击编辑Secrets。将secrets.toml的内容复制到文本区域。更多信息可在Secrets管理中找到。

Secrets manager screenshot

PyMongo包添加到您的requirements.txt文件中,最好固定其版本(将x.x.x替换为您想要安装的版本):

# requirements.txt pymongo==x.x.x

将以下代码复制到您的Streamlit应用程序中并运行。请确保调整您的数据库和集合的名称。

# streamlit_app.py import streamlit as st import pymongo # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): return pymongo.MongoClient(**st.secrets["mongo"]) client = init_connection() # Pull data from the collection. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): db = client.mydb items = db.mycollection.find() items = list(items) # make hashable for st.cache_data return items items = get_data() # Print results. for item in items: st.write(f"{item['name']} has a :{item['pet']}:")

看到上面的st.cache_data了吗?如果没有它,Streamlit 每次重新运行应用程序时(例如在小部件交互时)都会运行查询。有了st.cache_data,它只会在查询更改或10分钟后运行(这就是ttl的作用)。注意:如果你的数据库更新更频繁,你应该调整ttl或移除缓存,以便观众始终看到最新的数据。了解更多信息,请访问Caching

如果一切顺利(并且你使用了我们上面创建的示例数据),你的应用程序应该看起来像这样:

Finished app screenshot
forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。