R plumber API-安装的路由器未显示

我正在尝试使用Plumber(v0.4.6)构建API。我想使用多个.R文件(每个API的功能/端点一个),以避免使用所有功能制作一个巨大的.R文件。使用以下命令仅可以处理一个.R文件:

pr <- plumb("api/v1/plumber.R")
pr$run()

但是当我尝试将水管工文件拆分为两个单独的文件时,已安装的端点不显示:

root <- plumber$new("api/v1/plumber.R")
test <- plumber$new("api/v1/fct1.R")

root$mount("/test",test)
root$run()

这很奇怪,因为root$mounts显示了所有端点,而API仅显示了根的端点(图和总和):

# Plumber router with 2 endpoints,5 filters,and 1 sub-router.
# Call run() on this object to start the API.
├──[queryString]
├──[postBody]
├──[cookieParser]
├──[sharedSecret]
├──[logger]
├──/plot (GET)
├──/sum (POST)
├──/test
│  │ # Plumber router with 1 endpoint,4 filters,and 0 sub-routers.
│  ├──[queryString]
│  ├──[postBody]
│  ├──[cookieParser]
│  ├──[sharedSecret]
│  └──/test8 (GET)

这是两个文件的代码:

library(plumber)

#* @apiTitle Plumber Example API

#* Plot a histogram
#* @png
#* @get /plot
function() {
    rand <- rnorm(100)
    hist(rand)
}

#* Return the sum of two numbers
#* @param a The first number to add
#* @param b The second number to add
#* @post /sum
function(a,b) {
    as.numeric(a) + as.numeric(b)
}
  • fct1.R:
#* Echo back the input
#* @param msg The message to echo
#* @get /test8
function(msg = "") {
  list(msg = paste0("The message is: '",msg,"'"))
}

感谢您的帮助。

xiaoqingqiu22 回答:R plumber API-安装的路由器未显示

这在我相信的开发版本中已修复。这主要是水管工openapi文件生成问题,因为如果您使用httr或curl发送请求,端点仍然会响应。

devtools::install_github("rstudio/plumber")
,

解决方案/解释在这里:https://community.rstudio.com/t/functions-within-a-sourced-file-are-not-accessible-as-plumber-api-endpoints/64266或在这里: https://github.com/rstudio/plumber/issues/533

一种实现方法:

还可以创建一个新文件(例如api.R)并将所有端点放到那里(+在来源文件中命名函数)。为此,我们还将功能与API分开,例如:

api.R(新文件):

# plumber.R

source("./main.R")

#* Echo back the input
#* @param msg The message to echo
#* @get /echo
function(msg) {
  main.echo(msg)
}

#* Return "hello world"
#* @get /hello
function(){
  functions.hello()
}

main.R(类似于OP的问题中的plumber.R):

source("./functions.R")


main.echo = function(msg=""){
  list(msg = paste0("The message is: '",msg,"'"))
}

functions.R(类似于OP的问题中的fct1.R):

functions.hello = function(){
  "hello world"
}

然后

library(plumber)
pr = plumb("api.R")
pr$run()

然后可以访问/echo/hello端点。

本文链接:https://www.f2er.com/3160358.html

大家都在问