R Shiny/Restful Api通讯

use*_*739 25 rest r shiny shiny-server

我有一个闪亮的应用程序,在Json中获取输入文件通过分类器运行它并返回一个分类的Json对象.我希望应用程序能够与API通信.我希望API将文件发布到Shiny App,它将完成其工作并返回一个分类对象.基本上我希望Shiny应用程序位于后台,直到文件发布然后完成其工作.我知道我可以使用httr包中的GET从url获取文件.我可以把它放在shiny.server文件中,如果我知道get命令的文件名就可以了

但是,来自API的文件名将有所不同.那么有什么方法可以根据来自API的Post请求使这个动态化.

小智 6

如果您不必使用Shiny,则可以使用openCPU。OpenCPU自动将每个R软件包作为REST服务提供。我使用OpenCPU,工作正常!这是在另一个程序中使用R的最简单方法。


ism*_*gal 6

到目前为止,在这种情况下需要提到库(管道工)作为替代方案,但是以下示例展示了如何直接在闪亮中处理 POST 请求

它基于 Joe Cheng 的要点"http_methods_supported"建议向 UI添加一个属性并用于httpResponse应答请求。

下面的代码在后台 R 进程中启动一个闪亮的应用程序(这样做只是为了拥有单个文件 MRE - 当然,您可以将应用程序放在单独的文件中并删除 - 行r_bg)。应用程序启动后,父进程将 iris 发送data.frame到 UI。

在 UI 函数中req$PATH_INFO检查(请参阅uiPattern = ".*"),然后将数字列乘以 10 ( query_params$factor) 并作为 json 字符串发送回。

library(shiny)
library(jsonlite)
library(callr)
library(datasets)

ui <- function(req) {
  # The `req` object is a Rook environment
  # See https://github.com/jeffreyhorner/Rook#the-environment
  if (identical(req$REQUEST_METHOD, "GET")) {
    fluidPage(
      h1("Accepting POST requests from Shiny")
    )
  } else if (identical(req$REQUEST_METHOD, "POST")) {
    # Handle the POST
    query_params <- parseQueryString(req$QUERY_STRING)
    body_bytes <- req$rook.input$read(-1)
    if(req$PATH_INFO == "/iris"){
      postedIris <- jsonlite::fromJSON(rawToChar(body_bytes))
      modifiedIris <- postedIris[sapply(iris, class) == "numeric"]*as.numeric(query_params$factor)
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = jsonlite::toJSON(modifiedIris, dataframe = "columns")
      )
    } else {
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = '{"status": "ok"}'
      )
    }
  }
}
attr(ui, "http_methods_supported") <- c("GET", "POST")

server <- function(input, output, session) {}

app <- shinyApp(ui, server, uiPattern = ".*")
# shiny::runApp(app, port = 80, launch.browser = FALSE, host = "0.0.0.0")
shiny_process <- r_bg(function(x){ shiny::runApp(x, port = 80, launch.browser = FALSE, host = "0.0.0.0") }, args = list(x = app))

library(httr)
r <- POST(url = "http://127.0.0.1/iris?factor=10", body = iris, encode = "json", verbose())
recievedIris <- as.data.frame(fromJSON(rawToChar(r$content)))
print(recievedIris)
shiny_process$kill()
Run Code Online (Sandbox Code Playgroud)

另请查看此相关 PR,它提供了更多示例(还展示了如何使用session$registerDataObj),旨在更好地描述该httpResponse功能。