29

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

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

4

2 回答 2

9

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

于 2017-03-30T19:24:13.413 回答
0

这是基于 Joe Cheng 的 gist here"http_methods_supported" ,它建议向UI添加一个属性并用于httpResponse回答请求。

下面的代码在后台 R 进程中启动一个闪亮的应用程序。应用程序启动后,父进程将虹膜发送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()

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

于 2022-02-10T11:10:23.220 回答