如何在Streamlit应用中使用服务账户连接Google Drive并获取文件
使用服务账户在Streamlit中连接Google Drive
前置准备
- 在Google Cloud Console创建服务账户,下载JSON格式的密钥文件。
- 将目标Google Drive文件/文件夹共享给服务账户的邮箱(密钥文件里的
client_email字段),赋予查看者或更高权限。 - 安装依赖包:
pip install streamlit google-api-python-client google-auth-httplib2 google-auth-oauthlib
代码示例
方式1:使用Streamlit Secrets管理密钥(推荐,部署安全)
在Streamlit项目根目录创建
.streamlit/secrets.toml文件,把服务账户密钥的内容粘贴进去:[gcp_service_account] type = "service_account" project_id = "你的项目ID" private_key_id = "你的私钥ID" private_key = "你的私钥内容" client_email = "服务账户邮箱" client_id = "客户端ID" 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 = "你的证书URL"Streamlit应用代码:
import streamlit as st from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload import io # 加载服务账户凭证 credentials = service_account.Credentials.from_service_account_info( st.secrets["gcp_service_account"], scopes=["https://www.googleapis.com/auth/drive.readonly"] ) # 构建Drive服务 drive_service = build('drive', 'v3', credentials=credentials) # 查找名为"example"的文件(支持共享驱动器) def find_file(file_name): results = drive_service.files().list( q=f"name='{file_name}'", includeItemsFromAllDrives=True, supportsAllDrives=True, corpora="allDrives", fields="files(id, name)" ).execute() return results.get('files', []) # 下载文件 def download_file(file_id, file_name): request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() st.write(f"下载进度: {int(status.progress() * 100)}%") fh.seek(0) return fh # Streamlit界面逻辑 st.title("Google Drive 文件获取工具") target_file = "example" files = find_file(target_file) if files: st.success(f"找到文件: {files[0]['name']} (ID: {files[0]['id']})") if st.button("下载文件"): file_content = download_file(files[0]['id'], files[0]['name']) st.download_button( label="保存文件", data=file_content, file_name=files[0]['name'], mime="application/octet-stream" ) else: st.error(f"未找到名为'{target_file}'的文件,请检查权限或文件名")
方式2:直接加载本地密钥文件(适合本地测试)
如果是本地开发测试,可以直接加载密钥文件:
import streamlit as st from google.oauth2 import service_account from googleapiclient.discovery import build # 加载本地密钥文件 credentials = service_account.Credentials.from_service_account_file( "path/to/your/service-account-key.json", scopes=["https://www.googleapis.com/auth/drive.readonly"] ) # 后续构建服务、查找/下载文件的代码和方式1一致
注意事项
- 确保服务账户邮箱已被添加到目标Drive文件的共享列表中,否则会提示权限不足。
- 权限范围
scopes根据需求调整,比如需要修改文件用https://www.googleapis.com/auth/drive,只读用drive.readonly即可。 - 部署到Streamlit Cloud时,直接在项目设置里添加Secrets内容,不需要上传
.streamlit/secrets.toml文件。
内容的提问来源于stack exchange,提问作者CrazyHorse
相关产品推荐
相关产品推荐

