问题
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