Connect Streamlit to Google BigQuery
Introduction
本指南解释了如何从Streamlit社区云安全地访问BigQuery数据库。它使用了 google-cloud-bigquery库和 Streamlit的Secrets管理。
Create a BigQuery database
注意
如果您已经有一个想要使用的数据库,请随时跳到下一步。
对于这个例子,我们将使用BigQuery中的一个样本数据集(即shakespeare表)。如果你想创建一个新的数据集,请遵循Google的快速入门指南。
Enable the BigQuery API
通过Google Cloud Platform控制对BigQuery的编程访问。创建一个账户或登录并前往APIs & Services dashboard(如果需要,选择或创建一个项目)。如下所示,搜索BigQuery API并启用它:



Create a service account & key file
要从Streamlit社区云使用BigQuery API,您需要一个Google云平台服务账户(一种用于程序化数据访问的特殊账户类型)。前往服务账户页面并创建一个具有查看者权限的账户(这将允许账户访问数据但不能更改数据):



注意
如果按钮CREATE SERVICE ACCOUNT是灰色的,说明您没有正确的权限。请向您的Google Cloud项目管理员寻求帮助。
点击DONE后,您应该会返回到服务账户概览页面。为新账户创建一个JSON密钥文件并下载它:



Add the key file to your local app secrets
您的本地 Streamlit 应用程序将从应用程序根目录中的文件 .streamlit/secrets.toml 读取密钥。如果此文件尚不存在,请创建它,并将您刚刚下载的密钥文件内容添加到其中,如下所示:
# .streamlit/secrets.toml
[gcp_service_account]
type = "service_account"
project_id = "xxx"
private_key_id = "xxx"
private_key = "xxx"
client_email = "xxx"
client_id = "xxx"
auth_uri = "https://accounts.google.com/o/oauth2/auth"
token_uri = "https://oauth2.googleapis.com/token"
auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs"
client_x509_cert_url = "xxx"
重要
将此文件添加到.gitignore,不要将其提交到你的GitHub仓库!
Copy your app secrets to the cloud
由于上面的secrets.toml文件没有提交到GitHub,你需要将其内容单独传递给你部署的应用程序(在Streamlit社区云上)。转到应用程序仪表板,在应用程序的下拉菜单中,点击编辑Secrets。将secrets.toml的内容复制到文本区域。更多信息可在Secrets管理中找到。

Add google-cloud-bigquery to your requirements file
将google-cloud-bigquery包添加到您的requirements.txt文件中,最好固定其版本(将x.x.x替换为您想要安装的版本):
# requirements.txt
google-cloud-bigquery==x.x.x
Write your Streamlit app
将下面的代码复制到您的Streamlit应用程序中并运行它。如果您不使用示例表,请确保调整查询。
# streamlit_app.py
import streamlit as st
from google.oauth2 import service_account
from google.cloud import bigquery
# Create API client.
credentials = service_account.Credentials.from_service_account_info(
st.secrets["gcp_service_account"]
)
client = bigquery.Client(credentials=credentials)
# Perform query.
# Uses st.cache_data to only rerun when the query changes or after 10 min.
@st.cache_data(ttl=600)
def run_query(query):
query_job = client.query(query)
rows_raw = query_job.result()
# Convert to list of dicts. Required for st.cache_data to hash the return value.
rows = [dict(row) for row in rows_raw]
return rows
rows = run_query("SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10")
# Print results.
st.write("Some wise words from Shakespeare:")
for row in rows:
st.write("✍️ " + row['word'])
看到上面的st.cache_data了吗?如果没有它,Streamlit 每次重新运行应用程序时(例如在小部件交互时)都会运行查询。使用st.cache_data后,它只会在查询更改或10分钟后运行(这就是ttl的作用)。注意:如果您的数据库更新更频繁,您应该调整ttl或删除缓存,以便查看者始终看到最新数据。了解更多信息,请访问Caching。
或者,您可以使用pandas直接从BigQuery读取到数据框中!按照上述所有步骤,安装pandas-gbq库(别忘了将其添加到requirements.txt中!),并调用pandas.read_gbq(query, credentials=credentials)。更多信息请参阅pandas文档。
如果一切顺利(并且你使用了示例表),你的应用程序应该看起来像这样:

还有问题吗?
我们的 论坛 充满了有用的信息和Streamlit专家。