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

部署在shinyapps.io的Shiny App无法连接Google Drive的问题求助

解决Shiny App部署到shinyapps.io后无法写入Google Drive的问题

核心问题分析

本地运行正常但部署后失败,通常是认证机制、文件路径权限、Google Drive定位这几方面的环境差异导致的,以下是针对性解决方案:


1. 修正认证缓存设置

shinyapps.io服务器无法读取本地的.secret缓存目录,强制禁用缓存,确保每次用JSON密钥重新认证:

drive_auth(path = "www/rpercn-33529f052d82.json", cache = FALSE)

2. 用文件ID精确定位Google Drive文件

仅靠文件名responses.csv可能因重名或服务账号权限范围问题导致找不到文件,改用文件ID操作:

  • 打开Google Drive,右键responses.csv→「获取链接」,提取URL中的ID部分(比如https://drive.google.com/file/d/XXX/view里的XXX)
  • 修改下载和上传代码:
    # 下载文件
    temp_download <- tempfile(fileext = ".csv")
    drive_download(as_id("你的文件ID"), path = temp_download, overwrite = TRUE)
    
    # 上传覆盖文件
    temp_upload <- tempfile(fileext = ".csv")
    write.csv(new_data, temp_upload, row.names = FALSE)
    drive_upload(temp_upload, path = as_id("你的文件ID"), overwrite = TRUE)
    

3. 使用临时目录处理文件

shinyapps.io的当前工作目录权限受限,用tempfile()创建临时文件读写,避免权限错误:

  • 下载时写入临时文件,读取后自动清理
  • 上传时先将数据写入临时文件,再上传到Google Drive

4. 验证服务账号的完整权限

  • 确保服务账号邮箱被添加为responses.csv**和所在文件夹RPE_RCN2425**的编辑者,仅共享文件可能因文件夹权限限制导致操作失败
  • 检查Google Drive文件夹的共享设置,确认服务账号有编辑权限

5. 查看shinyapps.io日志定位具体错误

登录shinyapps.io后台,进入你的App页面,切换到「Logs」标签,里面会显示详细的错误信息(比如认证失败、文件未找到、权限不足等),是快速排查问题的关键。


修改后的示例代码片段

library(shiny)
library(tidyverse)
library(googledrive)

# 禁用缓存,使用JSON密钥认证
drive_auth(path = "www/rpercn-33529f052d82.json", cache = FALSE)

responses <- reactiveValues(data = data.frame(Nom = character(), Valeur = numeric(), Date = character()))

ui <- fluidPage(
  titlePanel("Échelle Visuelle Analogique"),
  textInput("name", "Nom du joueur"),
  sliderInput("eva", "Évaluation:", min = 0, max = 10, value = 5, step = 0.1),
  actionButton("submit", "Soumettre"),
  tableOutput("responses")
)

server <- function(input, output, session) {
  observeEvent(input$submit, {
    # 用临时文件下载Google Drive中的数据
    temp_download <- tempfile(fileext = ".csv")
    drive_download(as_id("替换为你的文件ID"), path = temp_download, overwrite = TRUE)
    
    old_data <- if(file.exists(temp_download)) {
      read.csv(temp_download, stringsAsFactors = FALSE)
    } else {
      data.frame(Nom = character(), Valeur = numeric(), Date = character())
    }
    
    # 拼接新数据
    new_data <- rbind(old_data, data.frame(
      Nom = input$name, 
      Valeur = input$eva, 
      Date = Sys.time()
    ))
    responses$data <- new_data
    
    # 用临时文件上传回Google Drive
    temp_upload <- tempfile(fileext = ".csv")
    write.csv(new_data, temp_upload, row.names = FALSE)
    drive_upload(temp_upload, path = as_id("替换为你的文件ID"), overwrite = TRUE)
  })
  
  output$responses <- renderTable({
    responses$data
  })
}

shinyApp(ui = ui, server = server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:00:11