R shiny-server:每个会话的用户特定目录

R shiny-server: User specific directory for each session

我的闪亮应用程序在服务器上,每次用户使用该应用程序时,都会在本地应用程序文件夹中生成一些文本文件(不同的内容,相同的文件名)。我担心当多个用户使用该应用程序时,导出的文本文件可能会发生冲突,因为文本文件的位置和文件名相同。

为了避免这种可能性,我正在考虑在用户启动会话时创建目录的方向,所有工作文件都导出到该目录,当会话关闭时,必须删除该目录。

关于如何处理这个问题有什么想法吗?有更好的解决方案吗?我如何检测会话何时关闭?如何计算活动会话数?

这在 shiny-server 环境和 shinyapps.io 上都能正常工作。 Tareef Kawaf 的一个工作示例。

ui.R

#ui.R
shinyUI(fluidPage(
  headerPanel("New directory issue"),
  wellPanel(
  helpText("I would like a new directory to be created each time a new connection is made to the app OR anytime new files are uploaded."),
  helpText("This app uploads one text file, creates a new directory, extracts first 5 lines and exports a text file with the contents."),
  helpText("Upload one text file with minimum 5 lines of content."),
  fileInput('upload', label=h4('Upload file(s):'), multiple=FALSE)
  ),
  mainPanel(
    tags$h3("Str of uploaded content"),
    verbatimTextOutput('display')
  )
))

server.R

#server.R

#Get current wd and print
currwd <- getwd()

#FUNCTION - new directory
fn_dir <- function(currwd=NULL)
{
  if(is.null(currwd)) stop("Argument 'currwd' is empty.\n")

  #Create new working directory
  newwd <- paste0(currwd,"/",format(Sys.time(),"%Y%m%d%H%M%S"))
  dir.create(newwd)
  newwd
}

shinyServer(function(input, output) {

  #REACTIVE - store
  store <- reactiveValues(currwd = currwd)

  #REACTIVE - complete input
  fn_getfilenames <- reactive({
    inputdata <- input$upload

    if (!is.null(inputdata))
    {
      store$newwd <- fn_dir(store$currwd)
      return(inputdata)
    }else{
      return(NULL)
    }
  })

  #OUTPUT
  output$display <- renderPrint({
    if (is.null(fn_getfilenames())) return(NULL)

    inputdata <- fn_getfilenames()

    #some stuff to export to working directory

    rcontent <- as.vector(scan(file = inputdata$datapath,what = "text",n = 10))

    full_file_path <- file.path(store$newwd,inputdata$name)
    write(x = rcontent, file = paste0(full_file_path,"-test.txt"))

    return(str(inputdata))
  })
})