首页 > 解决方案 > R googlesheets4 将令牌作为参数传递给 read_sheet

问题描述

只有当表格已经获得授权时,我才能阅读表格,

如果不是,则忽略后续的每一行代码,因为代码执行会不断要求令牌。有没有办法将令牌索引传递给 read_sheet 命令,或者事先授权访问?

   > aa <- read_sheet('https://docs.google.com/spreadsheets/d....', sheet='Akinesia', range="AC:AH")
The googlesheets4 package is requesting access to your Google account. Select a pre-authorised account or enter '0' to obtain a new token. Press Esc/Ctrl + C to abort.

1: chris.elliott@.....

Selection: 
Enter an item from the menu, or 0 to exit
Selection: 
Enter an item from the menu, or 0 to exit
Selection: 
Enter an item from the menu, or 0 to exit
Selection: aaX <- aa  %>% filter_all(any_vars(!is.na(.)))
Enter an item from the menu, or 0 to exit
Selection: akns <- aaX %>% pivot_longer(-genotype, names_to = "day", values_to = "nonresp")
Enter an item from the menu, or 0 to exit

标签: rgoogle-sheetstokengooglesheets4

解决方案


您需要进行提供不同身份验证方法的身份验证调用:

默认身份验证

尝试不带参数或使用与 Google 帐户关联的电子邮件地址的默认呼叫:

googlesheets4::gs4_auth(email = "chris.elliott@...")

服务帐号

您还可以传递与服务帐户关联的令牌文件:

googlesheets4::gs4_auth(path = "access_token.json")

path - 标识服务帐户的 JSON,采用 jsonlite::fromJSON() 的 txt 参数支持的一种形式(通常是文件路径或 JSON 字符串)。

漱口令牌

googlesheets4使用漱口包,所以你应该也可以像这样获得令牌:

library(gargle)
token <- token_fetch()
googlesheets4::gs4_auth(token = token)

推荐阅读