проблемы с закрытием сессии в чистых и очищенных временных файлах - PullRequest
0 голосов
/ 09 февраля 2019

Я новенький в блестящем, я создал приложение с взаимодействием с пользователем, они могут загружать свои файлы для обработки.Все нормально для визуализации и создания графиков, но у меня проблемы: почему я могу создать функцию для удаления загруженных файлов после закрытия сессии?

Я пытался с этими строками кода: (внутри функции сервера)

session$onSessionEnded(function() {
   if (!is.null(input$file1)) {
file.remove(input$file1$datapath)
  }
})

и:

onStop(function() {
   if (!is.null(input$file1)) {
file.remove(input$file1$datapath) }
})

с этим сообщением об ошибке:

Warning: Error in .getReactiveEnvironment()$currentContext: Operation 
not allowed without an active reactive context. (You tried to do 
something that can only be done from inside a reactive expression or 
observer.)
  41: stop
  40: .getReactiveEnvironment()$currentContext
  39: .subset2(x, "impl")$get
  38: $.reactivevalues

Я очень ценю любую помощь, большое спасибо!

1 Ответ

0 голосов
/ 09 февраля 2019

Добро пожаловать в переполнение стека!

input Переменная может быть доступна только из реактивного контекста, следовательно, ошибка.Реактивный контекст - это любой вызов render, observe, reactive, observeEvent или eventReactive.

Кроме того, временные файлы автоматически удаляются в конце сеанса.Вот немного измененный пример из https://shiny.rstudio.com/gallery/file-upload.html.

library(shiny)

# Define UI for data upload app ----
ui <- fluidPage(

  # App title ----
  titlePanel("Uploading Files"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Select a file ----
      fileInput("file1", "Choose CSV File",
                multiple = FALSE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),

      # Horizontal line ----
      tags$hr(),

      # Input: Checkbox if file has header ----
      checkboxInput("header", "Header", TRUE),

      # Input: Select separator ----
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),

      # Input: Select quotes ----
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),

      # Horizontal line ----
      tags$hr(),

      # Input: Select number of rows to display ----
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Data file ----
      tableOutput("contents")

    )

  )
)

# Define server logic to read selected file ----
server <- function(input, output) {

  output$contents <- renderTable({

    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, head of that data file by default,
    # or all rows if selected, will be shown.

    req(input$file1)

    # when reading semicolon separated files,
    # having a comma separator causes `read.csv` to error
    tryCatch(
      {
        df <- read.csv(input$file1$datapath,
                       header = input$header,
                       sep = input$sep,
                       quote = input$quote)

        cat(input$file1$datapath)
      },
      error = function(e) {
        # return a safeError if a parsing error occurs
        stop(safeError(e))
      }
    )

    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }

  })

}

# Create Shiny app ----
shinyApp(ui, server)

Запустите приложение и, пока оно выполняется, передайте путь к временному файлу в консоли.Как только вы закроете приложение и закончите сеанс, попробуйте повторить путь, и он будет удален.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...