You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Streamlit连接Google Sheets致应用卡顿,寻求优化解决方案

解决Streamlit与Google Sheets重复连接的性能问题

由于Streamlit每次交互都会重新运行全量代码,重复执行Google Sheets连接操作是导致卡顿的核心原因,你可以通过以下几种方式优化:

  • 使用Streamlit 1.23+版本的@st.cache_resource装饰器
    这个装饰器专门用来缓存全局资源(比如数据库连接、API客户端实例),只有当传入的参数发生变化时才会重新执行函数,完美适配你的场景。代码示例:

    import streamlit as st
    # 替换成你实际使用的Spread库导入语句
    from your_spread_module import Spread
    
    @st.cache_resource
    def get_sheets_resources(spreadsheetname, client):
        s = Spread(spreadsheetname, client=client)
        sh = client.open(spreadsheetname)
        return s, sh
    
    # 主逻辑中调用缓存后的函数
    s, sh = get_sheets_resources(spreadsheetname, client)
    
  • 旧版Streamlit用@st.experimental_singleton
    如果你的Streamlit版本低于1.23,用这个装饰器替代@st.cache_resource,功能一致,都是缓存单例资源:

    @st.experimental_singleton
    def get_sheets_resources(spreadsheetname, client):
        s = Spread(spreadsheetname, client=client)
        sh = client.open(spreadsheetname)
        return s, sh
    
  • 额外优化:缓存Google客户端实例
    如果创建Google Sheets客户端(client)的过程也比较耗时,把客户端的创建也放到缓存装饰器里,进一步减少重复操作:

    @st.cache_resource
    def get_google_client():
        # 这里写你的客户端初始化代码,比如从密钥文件创建凭证
        from googleapiclient.discovery import build
        from google.oauth2.service_account import Credentials
    
        creds = Credentials.from_service_account_file('your-service-account-key.json')
        client = build('sheets', 'v4', credentials=creds)
        return client
    
    # 先获取缓存的客户端
    client = get_google_client()
    # 再获取Sheets资源
    s, sh = get_sheets_resources(spreadsheetname, client)
    

内容的提问来源于stack exchange,提问作者Sina Kian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:46:05