Connect Streamlit to TigerGraph

本指南解释了如何从Streamlit社区云安全地访问TigerGraph数据库。它使用了pyTigerGraph库和Streamlit的Secrets management

首先,按照官方教程在TigerGraph云中创建一个TigerGraph实例,可以是博客视频。记下您的用户名、密码和子域名。

在本教程中,我们将使用COVID-19入门套件。在设置您的解决方案时,请选择“COVID-19分析”选项。

TG_Cloud_COVID19

一旦启动,请确保您的数据已下载并且查询已安装。

TG_Cloud_Schema

您的本地 Streamlit 应用程序将从应用程序根目录中的文件 .streamlit/secrets.toml 读取密钥。如果此文件尚不存在,请创建此文件,并添加您的 TigerGraph Cloud 实例用户名、密码、图名称和子域,如下所示:

# .streamlit/secrets.toml [tigergraph] host = "https://xxx.i.tgcloud.io/" username = "xxx" password = "xxx" graphname = "xxx"
priority_high

重要

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

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

Secrets manager screenshot

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

# requirements.txt pyTigerGraph==x.x.x

将下面的代码复制到您的Streamlit应用程序中并运行它。确保调整您的图表名称和查询。

# streamlit_app.py import streamlit as st import pyTigerGraph as tg # Initialize connection. conn = tg.TigerGraphConnection(**st.secrets["tigergraph"]) conn.apiToken = conn.getToken(conn.createSecret()) # Pull data from the graph by running the "mostDirectInfections" query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def get_data(): most_infections = conn.runInstalledQuery("mostDirectInfections")[0]["Answer"][0] return most_infections["v_id"], most_infections["attributes"] items = get_data() # Print results. st.title(f"Patient {items[0]} has the most direct infections") for key, val in items[1].items(): st.write(f"Patient {items[0]}'s {key} is {val}.")

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

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

Final_App
forum

还有问题吗?

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