Multipart/form-data 与 RestRserve

Multipart/form-data with RestRserve

我想公开一个接受 multipart/form-data、解析多部分内容和 returns csv 文件的端点。 (多部分输入包含一个 csv 数据集和处理指令)

我已经按照建议 使用 Rook::Multipart$parse() 与水管工完成了此操作。因为 plumber 不支持并行请求,所以我想用 RestRserve 重新实现它。以下将不起作用 - 管道工的输入是 class environmentRook::Multipart$parse() 假设),而 RestRserve 的输入是 class Request R6.

application = Application$new(content_type = "text/plain")
application$add_post("/echo", function(req, res) {
  multipart <- Rook::Multipart$parse(req$body)
  dta <- read_csv(multipart$dta$tempfile, trim_ws=FALSE)
  res$set_body(dta)
})

关于如何获得 multipart/form-data 输入以与 RestRserve 一起工作的任何想法?

RestRserve 在处理传入请求时解析多部分正文。结果,您在 request$files 中有原始 request$body 和元数据。 Request对象还提供了一个get_file方法来提取正文内容。让我展示应用程序和请求的示例:

# load packages
library(readr)
library(callr)
library(httr)

# run RestRserve in the background
ps <- r_bg(function() {
  library(RestRserve)
  library(readr)

  app = Application$new(content_type = "text/plain")
  app$add_post(
    path = "/echo",
    FUN = function(request, response) {
      # for debug
      str(request$body)
      str(request$files)
      # extract multipart body field
      cnt <- request$get_file("csv") # 'csv' from the upload form field
      # parse CSV
      dt <- read_csv(cnt)
      # for debug
      str(dt)
      # do something with dt
      identity(dt)
      # write result to temp file
      tmp <- tempfile()
      write_csv(dt, tmp)
      # set output body
      response$set_body(c(tmpfile = tmp))
      # or simply response$set_body(format_csv(dt))
    }
  )

  backend = BackendRserve$new()
  backend$start(app, http_port = 65080)
})

# wait for up
Sys.sleep(2L)

# check is alive
ps$is_alive()

# prepare CSV to upload
tmp <- tempfile()
write_csv(head(iris, 5), tmp)

# POST request with file
rs <- POST(
  url = "http:/127.0.0.1:65080/echo",
  body = list(csv = upload_file(tmp)),
  encode = "multipart"
)
# get response content
cat(content(rs))

# read log from the RestRserve
cat(ps$read_output())

# kill background prcoess
ps$kill()

有关此 class 中的字段和方法的更多详细信息,请参阅 ?Request