使用googlesheets4在R中通过Shiny连接到googlesheets4

问题描述

我正在尝试使用此example的更新版本通过Shiny连接到私有googlesheet,并将此应用程序部署在Shinyapps.io服务器上。该应用程序使用指定的预先存在的googlesheet,因此用户无需通过google帐户进行身份验证。

我遵循了此example(部分复制到此处),试图将令牌保存到我闪亮的应用中:

# prevIoUs googlesheets package version:
shiny_token <- gs_auth() # authenticate w/ your desired Google identity here
saveRDS(shiny_token,"shiny_app_token.rds")

,但尝试将其更新为googlesheets4,如下所示:

ss <- gs4_get("MY GOOGLE DOC URL") # do the authentication once,manually.
ss
gs4_has_token() # check that the token exists

# get token
ss_token <- gs4_token()
# save the token
save(ss_token,file = "APP PATH ... /data/tk.rdata")

然后在应用中,我将这段代码放在shinyApp()函数之外。

load("data/tk.rdata")

googlesheets4::gs4_auth(token = ss_token,use_oob = T)

在应用程序中,我使用从中获取的硬编码ID连接到该应用程序的google doc ss$spreadsheet_id以上。该应用程序可在本地运行。

尝试将应用程序部署到服务器后,出现错误“ ...无法获取google凭据。您是否在非交互式会话中运行googlesheets4?...等等”,我认为令牌将包含足够的信息。

如果有人可以向我指出设置此方法的指南,并对此方法(将令牌保存在Shinyapps.io上)是否安全,请发表评论

我看过其他示例,但似乎大多数用于googlesheets的先前版本

解决方法

只需按照this链接中的说明进行操作:

# designate project-specific cache
options(gargle_oauth_cache = ".secrets")
# check the value of the option,if you like
gargle::gargle_oauth_cache()
# trigger auth on purpose to store a token in the specified cache
# a broswer will be opened
googlesheets4::sheets_auth()
# see your token file in the cache,if you like
list.files(".secrets/")
# sheets reauth with specified token and email address
sheets_auth(
 cache = ".secrets",email = "youremail"
 )