Hi,
My code takes in an input csv and is supposed to output another csv or xlsx. I tried using XLSX content type from https://github.com/trestletech/plumber/blob/master/R/content-types.R, but it is throwing an exception every time without any mention about the exception type. Is there a way to do this?
@Amalabdu Would you mind provide a minimal reproducible example? I'm not sure what your problem is.
If we have to return a PDF file then we use something like
function(){
tmp <- tempfile()
pdf(tmp)
plot(1:10, type="b")
text(4, 8, "PDF from plumber!")
dev.off()
readBin(tmp, "raw", n=file.info(tmp)$size)
}
Now what if I want to return a CSV file? As in there is a model that runs and outputs a CSV. So can we output a CSV through Plumber, using XLSX or otherwise?
@Amalabdu The example code below should solve your problem. It works for me.
BTW, using three backticks (```) to enclose the code makes your code easier to read.
serializer_csv <- function(){
function(val, req, res, errorHandler){
tryCatch({
res$setHeader("Content-Type", "text/plain")
res$setHeader("Content-Disposition", 'attachment; filename="xxx.csv"')
res$body <- paste0(val, collapse="\n")
return(res$toResponse())
}, error=function(e){
errorHandler(req, res, e)
})
}
}
plumber::addSerializer("csv", serializer_csv)
plumber::plumber$new("plumber-csv.R")$run(port = 8833)
#* @serializer csv
#* @get /csv
function() {
df <- data.frame(CHAR = letters, NUM = rnorm(length(letters)), stringsAsFactors = F)
csv_file <- tempfile(fileext = ".csv")
on.exit(unlink(csv_file), add = TRUE)
write.csv(df, file = csv_file)
readLines(csv_file)
}
Thanks a lot @shrektan!! It works perfectly.
The code below:
plumber::addSerializer("csv",
serializer_csv)
...throws an error if it's done a second time "Already have a serializer by the name of csv".
How can I check the serializers first to see if this exists, or enforce it to be overridden?
Locking thread. Please open a new issue referencing this one for context.
@willwright76 Thank you for the issue! I have added it in #410
Most helpful comment
Thanks a lot @shrektan!! It works perfectly.