如何使用基本身份验证发出并发 HTTP 请求

Ben*_*Ben 2 curl r rcurl httr

我的目标是从 Shopify 导入客户的订单历史记录。Shopify 只允许我每个请求导入 250 个订单,但我的客户有数千个订单。

这是(基本上)我当前使用httr 的工作解决方案,它非常慢

fetchedList <- list()

# Loop through pages of orders and collect them
for(pg in 1:10){

  requestURL <- paste0("https://abc-store.myshopify.com/admin/orders.json?page=", p)

  fetched <- httr::GET(
    url = requestURL,
    httr::add_headers(Accept = "application/json"),
    httr::authenticate(user = "foo", password = "bar")
  )

  # Append the fetched response to fetchedList 
  fetchedList <- c(fetchedList, list(fetched))
}

# Process the results...
Run Code Online (Sandbox Code Playgroud)

我想通过发出多个并发请求来加快速度。我怎样才能实现这个目标?似乎curlRCurl都支持这一点,但我对HTTP 相当陌生,无法让任何一个解决方案工作。

Jer*_*oen 5

您应该使用多 api 来执行并发请求。请参阅手册页或小插图中有关异步请求的?multi_run部分。

还有一些包封装了多 api,以使其变得更容易。如果您想真正喜欢async包,则可以使用crul(注意 crul 不是拼写错误:)或更多包。


Ben*_*Ben 5

感谢 @Jeroen 给我指出了crul包。当时,crul 实际上还没有设置此功能,但我与维护人员进行了交谈,他实现了它。所以,从 v 0.5.2.9100 开始我可以做

dd <- Async$new(urls = c(
  'https://abc-store.myshopify.com/admin/orders.json?page=1',
  'https://abc-store.myshopify.com/admin/orders.json?page=2',
  'https://abc-store.myshopify.com/admin/orders.json?page=3'
))
res <- dd$get(auth = auth(user = "foo", pwd = "bar"))
vapply(res, function(z) z$status_code, double(1))
vapply(res, function(z) z$success(), logical(1))
lapply(res, function(z) z$parse("UTF-8"))
Run Code Online (Sandbox Code Playgroud)