7

我正在尝试使用此示例的更新版本通过闪亮连接到私人 googlesheet,并将此应用程序部署在 shinyapps.io 服务器上。由于应用程序使用指定的预先存在的 googlesheet,因此用户无需对 google 帐户进行身份验证。

我已经按照这个例子(部分复制在这里),试图将令牌保存到我闪亮的应用程序中:

# 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)

在应用程序中,我使用从 ss$spreadsheet_id上面获得的硬编码 id 从应用程序连接到谷歌文档。该应用程序在本地运行。

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

如果有人能指出我的设置指南,并评论这种方法(在 shinyapps.io 上保存令牌)是否安全,我将不胜感激?

我看过其他示例,但似乎大多数是针对以前版本的googlesheets

4

2 回答 2

7

2021 年 7 月 21 日,googlesheets4在发布 v1.0.0 时弃用了它的一些功能

我已经更新了 volfi 的答案以使用 googlesheets4 v1.0.0。
它在部署到 shinyapps.io 时也有效。

设置非交互式身份验证

library(googlesheets4)
    
# Set authentication token to be stored in a folder called `.secrets`
options(gargle_oauth_cache = ".secrets")

# Authenticate manually
gs4_auth()

# If successful, the previous step stores a token file.
# Check that a file has been created with:
list.files(".secrets/")

# Check that the non-interactive authentication works by first deauthorizing:
gs4_deauth()

# Authenticate using token. If no browser opens, the authentication works.
gs4_auth(cache = ".secrets", email = "your@email.com")

示例 - 将数据添加到 Google 表格

在 Google 表格上创建一个 Google表格并复制表格的网址。

library(googlesheets4)
gs4_auth(cache=".secrets", email="your@email.com")

ss <- gs4_get("https://docs.google.com/path/to/your/sheet")
sheet_append(ss, data.frame(time=Sys.time()))

如果将您的应用程序部署到 shinyapps.io,请确保将文件部署到文件.secrets夹中。

于 2021-12-03T14:04:11.360 回答
5

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

# 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"
 )
于 2020-09-16T10:05:19.713 回答