我正在尝试创建一个
R
plumber
端点,它接受 .rds
文件和表示保存到磁盘时使用的文件名的字符串。我在下面的示例中取得了成功,但是每个请求都有水管工报告以下消息
No suitable parser found to handle request body type .
如何实现以“正确”方式解析
.rda
文件和字符串到管道工 api 的目标,而不需要任何消息,并且最好还提供 swagger
支持?
水管工.R
library(plumber)
#* Save an rds file to disk
#* @post /write_rds
#* @parser multi
#* @parser rds
#* @parser text
#* @parser none
function(req) {
multi <- mime::parse_multipart(req)
file_path <- multi$file_path
rds_file <- readRDS(multi$rds_file$datapath)
save(rds_file,file = file_path)
TRUE
}
使用 httr 包发出的请求
library(magrittr)
library(httr)
tmpfile <- tempfile()
saveRDS(iris,file = tmpfile)
res <-
POST(
"http://127.0.0.1:8966/write_rds",
body = list(
# send the file with mime type `"application/rds"` so the RDS parser is used
rds_file = upload_file(tmpfile, "application/rds"),
file_path="test.rds"
),encode = "multipart"
) %>%
content()
res
我已设法停止显示消息,但我不认为这是最干净的解决方案。事实证明,从
#* @parser rds
对象中拉出时,不需要 req
标签。以下解决方案的缺点是未提供 R 函数的其他参数,必须从 req
中提取
library(plumber)
#* Save an rds file to disk
#* @post /write_rds
#* @param rds_file:[file]
#* @param file_path:[str]
function(req, rds_file, file_path) {
multi <- mime::parse_multipart(req)
# function does not receive the `file_path` argument
# despite being in the post body
cat("file_path is '", file_path, "'\n")
#multi contains a list with enough info to get POST content
str(multi)
#extract `file_path` from request body
file_path <- multi$file_path
#read the content of the rds (in this case, head(iris))
rds_file <- readRDS(multi$rds_file$datapath)
print(rds_file)
#write to disk
saveRDS(rds_file, file = file_path)
TRUE
}
library(magrittr)
library(httr)
tmpfile <- tempfile()
dat <- head(iris)
saveRDS(dat,file = tmpfile)
res <-
POST(
"http://127.0.0.1:8966/write_rds",
body = list(
# send the file with mime type `"application/rds"` so the RDS parser is used
rds_file = upload_file(tmpfile, "application/rds"),
file_path="testfile.rds"
),encode = "multipart"
) %>%
content()
res