【问题标题】:Shiny Server - how to use session$onSessionEnded()闪亮的服务器 - 如何使用 session$onSessionEnded()
【发布时间】:2023-04-05 21:10:01
【问题描述】:

我正在尝试在用户浏览我闪亮的应用程序时跟踪他们的活动。我将函数放置在将行写入临时文件的特定位置。我想要的是有一个在用户会话结束时调用的函数。

根据文档:

> ?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.

我试过用这个:

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

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

我在这里错过了什么?

【问题讨论】:

  • onSessionEnded 中尝试不带参数的函数:function() {...}

标签: r shiny shiny-server


【解决方案1】:

您好,我不知道您是如何构建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)

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

users_data <- data.frame(USERS = session$user, START = Sys.time())

【讨论】:

  • 有什么办法可以在会话结束时只指定一个会话做某事。例如session$onSessionEnded( function(){ if(userID==1) cat("Do Something Wild") })
  • @Jordan 请检查我的回答
【解决方案2】:

基于@Victorp 的回答并回复关于session$onSessionEnded 参数的评论。可以使用默认参数向函数添加参数:

server <- function(input, output, session) {
  # This code will be run once per user
  users_data <- data.frame(USERS = session$user, START = Sys.time())

  # This code will be run after the client has disconnected
  session$onSessionEnded(function(userID = users_data$USERS) {
      if(userID==1){
          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)

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 2016-05-23
    • 2021-11-07
    • 2021-03-10
    • 2016-10-24
    • 1970-01-01
    • 2018-02-16
    • 2015-10-05
    • 2016-12-28
    相关资源
    最近更新 更多