【发布时间】:2018-09-10 16:36:00
【问题描述】:
有没有办法将 API 密钥永久保存到我的 R 配置文件或环境中,这样我就不必在每个会话中都使用 set_key()?我不喜欢在我的代码中保存密钥,因为它在 github 上。
【问题讨论】:
有没有办法将 API 密钥永久保存到我的 R 配置文件或环境中,这样我就不必在每个会话中都使用 set_key()?我不喜欢在我的代码中保存密钥,因为它在 github 上。
【问题讨论】:
您可以将其放入您的 First 函数中,该函数位于您的 Rprofile.site 文件中。
我不确定你在哪个平台上,但这应该可以工作
rfile <- list.files(path = Sys.getenv("R_HOME"), recursive = TRUE,
full.names = TRUE, pattern = "Rprofile.site")
file.edit(rfile)
Rprofile.site 现在应该在您的编辑器中打开。注意:您可能需要调整系统上文件的文件权限才能写入(保存)
将此添加到.First
# Things you might want to change
# options(papersize="a4")
# options(editor="notepad")
# options(pager="internal")
# set the default help type
# options(help_type="text")
.First <- function(){
# Your string api key
google_api_key <- "12345"
# Use assign to explicitly set the environment in which to populate the key
assign("my_google_key", google_api_key, envir = .GlobalEnv)
}
保存文件并重启R
如果您的 api 密钥是 Token 对象,例如 oauth,只需保存到文件并读入并分配给 google_api_key 值。如:
.First <- function(){
# Your oauth api key read in from file
google_api_key <- readRDS("~/.hide_google_token.rds")
# Use assign to explicitly set the environment in which to populate the key
assign("google_oauth_token", google_api_key, envir = .GlobalEnv)
}
【讨论】: