2

我想公开一个接受多部分/表单数据的端点,解析多部分内容并返回一个 csv 文件。(多部分输入包含一个 csv 数据集和处理指令)

我已经按照这里Rook::Multipart$parse()的建议与水管工一起完成了这项工作。因为管道工不支持并行请求,所以我想用 RestRserve 重新实现它。以下内容不起作用 - 管道工的输入属于 class (假设),而 RestRserve 的输入属于 class 。environmentRook::Multipart$parse()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)
})

关于如何让多部分/表单数据输入与 RestRserve 一起工作的任何想法?

4

1 回答 1

2

RestRserve在处理传入请求时解析多部分正文。结果,您request$bodyrequest$files. Requestobject 还提供了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()

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

于 2020-03-19T11:34:19.037 回答