gpt4 book ai didi

r - 带有 RestRserve 的多部分/表单数据

转载 作者:行者123 更新时间:2023-12-04 10:23:27 24 4
gpt4 key购买 nike

我想公开一个接受多部分/表单数据的端点,解析多部分内容并返回一个 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 一起使用的任何想法?

最佳答案

RestRserve在处理传入请求时解析多部分正文。结果你有一个原始 request$bodyrequest$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有关此类中的字段和方法的更多详细信息。

关于r - 带有 RestRserve 的多部分/表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60724116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com