【问题标题】:API that takes a file as input parameter将文件作为输入参数的 API
【发布时间】:2019-09-23 17:48:44
【问题描述】:

有人要求我创建一个 API,它将文件作为输入并将该文件放在服务器上的目录中。这是为了消除应用程序直接与文件夹交互的需要。

我之前构建过 API(在 R 中使用 Plumber)并且可以处理字符串输入 - 我只是难以将文件作为输入参数。管道工文档都没有解释如何做到这一点。这甚至可以做到吗?有没有办法在 Python 中做到这一点?

【问题讨论】:

  • 我认为您可以使用服务器位置和 body 参数中的文件调用 httr::POST() - 查看文档以获取具体示例。
  • Python 模块requests 可以让你做同样的事情。

标签: python r rest api plumber


【解决方案1】:

您可以使用plumberRook 通过POST 上传文件。

这是一个小例子

api.R

library(plumber)
library(Rook)

#* Upload file
#* @param upload File to upload
#* @post /uploadfile
function(req, res){
  fileInfo <- list(formContents = Rook::Multipart$parse(req))
  ## The file is downloaded in a temporary folder
  tmpfile <- fileInfo$formContents$upload$tempfile
  ## Copy the file to a new folder, with its original name
  fn <- file.path('~/Downloads', fileInfo$formContents$upload$filename)
  file.copy(tmpfile, fn)
  ## Send a message with the location of the file
  res$body <- paste0("Your file is now stored in ", fn, "\n")
  res
}

运行服务器

plumber::plumb('api.R')$run(port = 1234)

使用 curl 发送文件 test.txt

curl -v -F upload=@test.txt http://localhost:1234/uploadfile

【讨论】:

  • 这太好了 - 非常感谢。让它在 Python 中工作,但更喜欢在 R 中这样做。谢谢!
猜你喜欢
  • 2018-10-15
  • 2019-03-01
  • 2019-02-27
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多