Shiny Server - 如何使用session $ onSessionEnded()

Mar*_*ark 7 r shiny shiny-server

我正试图通过我的闪亮应用程序跟踪用户活动.我将函数放在特定位置,将行写入临时文件.我想要的是拥有一个在用户会话结束时调用的函数.

根据文件:

> ?session
> onSessionEnded(callback)  
      Registers a function to be called after the client has disconnected. Returns a function that can be called with no arguments to cancel the registration.
Run Code Online (Sandbox Code Playgroud)

我试着用这个:

session$onSessionEnded(function(x){
  a = read_csv(shinyActivityTmpFile_000)
  write_csv(a,'C:\\Users\\xxxx\\Desktop\\test.csv')
})
Run Code Online (Sandbox Code Playgroud)

但什么都没发生. shinyActivityTmpFile_000是一个全局文件引用.当用户点击按钮并执行操作时,应用程序将以CSV格式写入此文件.我只是想把它从临时存储移动到永久存储.最终我希望将函数写入数据库但是为了测试我只是想尝试一个在应用程序关闭时运行的函数.

我在这里错过了什么?

Vic*_*orp 16

嗨我不知道你是如何构建shinyActivityTmpFile文件的,但是对于使用onSessionEnded你可以查看这个例子,它在文件中写入应用程序启动时和应用程序关闭时的日期时间:

library("shiny")
ui <- fluidPage(
  "Nothing here"
)
server <- function(input, output, session) {
  # This code will be run once per user
  users_data <- data.frame(START = Sys.time())

  # This code will be run after the client has disconnected
  session$onSessionEnded(function() {
    users_data$END <- Sys.time()
    # Write a file in your working directory
    write.table(x = users_data, file = file.path(getwd(), "users_data.txt"),
                append = TRUE, row.names = FALSE, col.names = FALSE, sep = "\t")
  })
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

如果您使用带身份验证的服务器,则可以使用以下命令检索用户名:

users_data <- data.frame(USERS = session$user, START = Sys.time())
Run Code Online (Sandbox Code Playgroud)