繁体   English   中英

闪亮的服务器。 打印JSON作为结果输出

[英]shiny-server. Print JSON as a result output

我正在尝试使用shiny-server作为进程服务器:接收URL请求,处理R子例程并输出JSON作为结果。 但我无法在JSON中直接将输出打印到浏览器。

是否可以这种方式使用闪亮的服务器?

PD:我知道这不是闪亮服务器的典型用法

非常感谢!

今天我发现这个包裹R函数RPC / REST-ish的其他包:

https://github.com/trestletech/plumber

通过注释R函数,如下所示:

#' @get /mean
normalMean <- function(samples=10){
  data <- rnorm(samples)
  mean(data)
}

#' @post /sum
addTwo <- function(a, b){
  as.numeric(a) + as.numeric(b)
}

您可以将其公开为web api:

> library(plumber)
> r <- plumb("myfile.R")  # Where 'myfile.R' is the location of the file shown above
> r$run(port=8000)

听起来您正在尝试使用闪亮的服务器构建REST或JSON-RPC Web服务。 目前这不可能(使用Shiny Server v1.2)。

闪亮的服务器呈现文本/ html模板(shinyUI)页面并使用WebSocket回调来填充内容。 @ScottChamberlain的答案将在Web浏览器的HTML正文中呈现JSON。 这不适用于程序化Web请求。

我发现rApacheRookRJSONIO是JSON Web服务的强大且高性能的解决方案。 您需要熟悉Apache Web服务器的配置,并根据您的平台构建Apache模块。

rApache是一个将R嵌入Apache Web服务器的模块,允许您托管Rook,brew和其他R框架。

Rook定义了R应用程序和Web服务器之间的接口。 这使得使用正确的内容类型轻松交付JSON有效负载。

其他选择包括:

  • OpenCPU - 专用的R HTTP服务器,明确支持JSON RPC
  • node-rio - 与RServe接口的node.js服务器
  • FastRWeb - 用于将Web服务器连接到RServe的CGI或PHP接口
  • RServe - 二进制R TCP / IP服务器
  • httpuv - R的HTTP和WebSocket服务器库
  • R内置rhttpd - 不建议用于生产

这个简单的解决方案呢?

https://gist.github.com/sckott/7478126

server.r

require(shiny)
require(RJSONIO)

shinyServer(function(input, output) {
  output$jsonoutput <- renderText({
    toJSON(list(a = 10, b = 12))
  })
})

ui.r

require(shiny)

shinyUI(bootstrapPage(
  mainPanel(
   textOutput(outputId="jsonoutput")
  )
))

文字打印不漂亮,但......

另外,请看一下Shiny邮件列表上的这个答案: https ://groups.google.com/forum/#!searchin/shiny-discuss/json $ 20output / shiny-discuss / -JYOXAeLCtI / kslvMve_FmIJ - Shiny isn我的确设计用于将数据作为API提供。

黑客闪亮怎么样?

httpHandler = function(req){
 message = list(value="hello")
 return(list(status = 200L,
             headers = list('Content-Type' = 'application/json'),
             body = toJSON(message)))
}
shiny:::handlerManager$addHandler(shiny:::routeHandler("/myEndPoint",httpHandler) , "a_unique_id")

# then start your shiny app ...

然后将浏览器指向http://127.0.0.1:[shinyport]/myEndPoint/

对我来说,它使用verbatimTextOutput工作:

ui.R

verbatimTextOutput(outputId="jsonoutput")

server.R - 假设getMainData()返回要转换为json的数据

output$jsonoutput <- renderText({

data <- getMainData()


result <- jsonlite::prettify(jsonlite::toJSON(data, auto_unbox = TRUE), 4)

return(result)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM