Read local csv in plumber API

狂风中的少年 提交于 2021-02-16 21:06:36

问题


I want to read and process a csv file by R using plumber.

So far I found an ongoing discussion regarding file uploads in plumber on GitHub (though regarding binary files) and this SO answer (transforming JSON file), both supposing the use of postBody.

I therefore started with this endpoint:

library(plumber)

#* parse csv file
#* @param req  the request object
#* @post /file
function(req) {
  result <- req$postBody
  return(result)
})

When testing the endpoint using httr, I can read the file as JSON list but fail processing the data in the next step.

upload_csv <- httr::upload_file("file.csv")
resp <- httr::POST(
  url = url,
  path = "echo",
  body = upload_csv
)
httr::content(resp)

Also, testing the endpoint yields two warnings

Warning in if (stri_startswith_fixed(body, "{")) { :
  the condition has length > 1 and only the first element will be used
Warning in if (stri_startswith_fixed(qs, "?")) { :
  the condition has length > 1 and only the first element will be used

回答1:


You can use the Rook package for that

library(plumber)
library(Rook)

#* parse csv file
#* @param req the request object
#* @post /file
function(req) {
  file <- Rook::Multipart$parse(req)$req$tempfile
  result <- read.csv(file)
  result
}

The warnings are still there using the current CRAN version of the package, but are removed in the github version (see here for more info).



来源:https://stackoverflow.com/questions/57648350/read-local-csv-in-plumber-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!