3

我的数据库密码存储在pgpass.conf文件中。我从 R 连接到数据库RPostgres,没有指定密码,所以它是从 读取的pgpass.conf,如下所示:

con <- dbConnect(RPostgres::Postgres(), 
                 dbname = "dbname",
                 user = "username",
                 host = "localhost",
                 port = "5432")

它通常工作得很好,但是当我尝试从闪亮的应用程序连接到数据库时它不起作用。连接定义与上面完全相同,放在server.R脚本中。当我使用默认参数运行 Shiny 应用程序时,出现错误:

FATAL:  password authentication failed for user "username"
password retrieved from file "C:\Users\...\AppData\Roaming/postgresql/pgpass.conf"

当连接定义中明确给出密码时:

con <- dbConnect(RPostgres::Postgres(), 
                 dbname = "dbname",
                 user = "username",
                 host = "localhost",
                 password = "mypass",
                 port = "5432")

一切正常。

为了让事情变得更奇怪,当闪亮的端口设置为某个值时,例如:shiny::runApp(port = 4000),在没有指定密码的情况下建立连接,但仅是第一次 - 这意味着当应用程序在同一个 R 会话中关闭并重新打开时,会发生错误再次。

我已经测试了包'RPostgreSQL' - 它也不起作用,只有错误消息不同:

Error in postgresqlNewConnection(drv, ...) : 
  RS-DBI driver: (could not connect postgres@localhost on dbname "dbname")

我使用 32 位 R,但我已经在 64 位上对其进行了测试,结果是一样的。Shiny 应用程序在浏览器 (Chrome) 和 Rstudio Viewer 中运行。

这是我的会话信息:

R version 3.2.2 (2015-08-14)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Polish_Poland.1250  LC_CTYPE=Polish_Poland.1250        LC_MONETARY=Polish_Poland.1250
[4] LC_NUMERIC=C                   LC_TIME=Polish_Poland.1250    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RPostgres_0.1  DBI_0.3.1.9008 shiny_0.12.2  

loaded via a namespace (and not attached):
[1] R6_2.1.1         htmltools_0.2.6  tools_3.2.2      rstudioapi_0.3.1     Rcpp_0.12.1.3    jsonlite_0.9.17  digest_0.6.8    
[8] xtable_1.7-4     httpuv_1.3.3     mime_0.4         RPostgreSQL_0.4
4

2 回答 2

2

在 Shiny 和您的系统 R GUI 之间运行命令的环境可能有所不同。我通过将我的凭据存储在Renviron 文件中来解决这个问题:

readRenviron("~/.Renviron")
con <- dbConnect(RPostgres::Postgres(), 
                 dbname = Sys.getenv('pg_db'),
                 user = Sys.getenv('api_user'),
                 ...)

问题是你可以为登台和生产环境维护单独的 Renvirons。这允许您的脚本使用 acommandArgs()来指定它应该使用的数据库凭据:

#!/usr/bin/env Rscript
environ_path <- switch(commandArgs(),
                  'staging' = {"~/staging.Renviron"},
                  'production' = {"~/production/Renviron"})

readRenviron(environ_path)

然后从 BASH:

Rscript analysis.R staging
于 2015-12-01T17:52:24.373 回答
0

错误在 Postgresql 中:

C:\Users\...\AppData\Roaming/postgresql/pgpass.conf

文件路径包含“/”而不是“\”

于 2020-10-22T19:35:43.347 回答