使用 googlesheets4 通过 R 中的闪亮连接到 googlesheets

CCI*_*CID 5 r shiny google-sheets-api googlesheets4

我正在尝试使用此示例的更新版本通过 Shine 连接到私有 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")

Run Code Online (Sandbox Code Playgroud)

但尝试将其更新为 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")
Run Code Online (Sandbox Code Playgroud)

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

load("data/tk.rdata")

googlesheets4::gs4_auth(token = ss_token, use_oob = T)
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Joh*_*rud 20

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")
Run Code Online (Sandbox Code Playgroud)

示例 - 将数据添加到 Google Sheet

在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()))
Run Code Online (Sandbox Code Playgroud)

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

  • gs4_auth() 添加一个名为 .secrests/ 的文件夹,并在其中放入一个令牌文件。 (2认同)

小智 6

只需按照此链接中的说明操作即可:

# 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"
 )
Run Code Online (Sandbox Code Playgroud)

  • 这正在闪亮的服务器上运行。对此方法与服务帐户的安全性有何评论?例如,在闪亮的服务器上拥有 .secrets 缓存? (2认同)
  • 知道为什么“googlesheets4::sheets_auth()”不再包含在包中吗?你有什么解决办法吗? (2认同)