到目前为止,在这种情况下需要提到library(
plumber)作为替代方案,但以下示例展示了如何直接在shiny中处理POST请求。
它基于Joe Cheng的gist
here,建议在UI中添加属性“http_methods_supported”,并使用httpResponse来回答请求。
以下代码在后台R进程中启动一个闪亮的应用程序(这仅是为了拥有单个文件MRE - 当然,您可以将应用程序放在单独的文件中并删除r_bg行)。启动应用程序后,父进程将iris数据框发送到UI。
在UI函数中,检查req$PATH_INFO(请参见uiPattern = ".*"),然后将数字列乘以10(query_params$factor)并作为json字符串发送回来。
library(shiny)
library(jsonlite)
library(callr)
library(datasets)
ui <- function(req) {
if (identical(req$REQUEST_METHOD, "GET")) {
fluidPage(
h1("Accepting POST requests from Shiny")
)
} else if (identical(req$REQUEST_METHOD, "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_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
函数。