【发布时间】:2026-02-01 16:15:01
【问题描述】:
我想根据任意数量的输入变量动态调用管道工 API。我需要将 curl 输入映射到函数名的输入。例如,如果函数有一个输入hi,那么curl -s --data 'hi=2' 意味着hi=2 应该作为输入参数传递给函数。这可以直接在 R 中使用 match.call() 完成,但在通过管道工 API 调用它时会失败。
取函数
#' @post /API
#' @serializer unboxedJSON
tmp <- function(hi) {
out <- list(hi=hi)
out <- toJSON(out, pretty = TRUE, auto_unbox = TRUE)
return(out)
}
tmp(hi=2)
out: {hi:2}
然后
curl -s --data 'hi=10' http://127.0.0.1/8081/API
out: {\n \"hi\": \"2\"\n}
一切看起来都不错。但是,取函数
#' @post /API
#' @serializer unboxedJSON
tmp <- function(...) {
out <- match.call() %>%
as.list() %>%
.[2:length(.)] # %>%
out <- toJSON(out, pretty = TRUE, auto_unbox = TRUE)
return(out)
}
tmp(hi=2)
out: {hi:2}
然后
curl -s --data 'hi=10' http://127.0.0.1/8081/API
out: {"error":"500 - Internal server error","message":"Error: No method asJSON S3 class: R6\n"}
在实践中,我真正想做的是加载我的 ML 模型以使用管道工 API 预测分数。例如
model <- readRDS('model.rds') # Load model as a global variable
predict_score <- function(...) {
df_in <- match.call() %>%
as.list() %>%
.[2:length(.)] %>%
as.data.frame()
json_out <- list(
score_out = predict(model, df_in) %>%
toJSON(., pretty = T, auto_unbox = T)
return(json_out)
}
此函数在本地运行时按预期工作,但通过 API 通过curl -s --data 'var1=1&var2=2...etc' http://listen_address 运行
我收到以下错误:{"error":"500 - Internal server error","message":"Error in as.data.frame.default(x[[i]], optional = TRUE): cannot coerce class \"c(\"PlumberResponse\", \"R6\")\" to a data.frame\n"}
【问题讨论】:
标签: r api machine-learning deployment plumber