具有RestRserve的多部分/表单数据

问题描述 投票:1回答:1

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

我已经按照建议的Rook::Multipart$parse()使用here完成了对水管工的操作。由于水管工不支持并行请求,因此我想用RestRserve重新实现。以下操作无效–水管工的输入为environment类(Rook::Multipart$parse()假定),而RestRserve的输入为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一起使用的任何想法?

r multipartform-data restrserve
1个回答
1
投票

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

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

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

  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
      response$set_body(cnt)
    }
  )

  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()
© www.soinside.com 2019 - 2024. All rights reserved.