我想公开一个接受多部分/表单数据,解析多部分内容并返回一个csv文件的端点。(多部分输入包含csv数据集和处理指令)
我已经Rook::Multipart$parse()
按照这里的建议使用管道工来完成此操作。因为水管工不支持并行请求,所以我想用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一起使用的任何想法?
RestRserve
在处理传入请求时解析多部分主体。结果,您在中有一个原始数据request$body
和元数据request$files
。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()
请参阅?Request
以获取有关此类中字段和方法的更多详细信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句