在 API 调用 (R) 中使用 httr::RETRY() 函数实现调用重试

发布于 2025-01-20 20:25:30 字数 2283 浏览 3 评论 0 原文

我使用 un comtrade comtrade data api at r

library(rjson)

get.Comtrade <- function(url="http://comtrade.un.org/api/get?"
                         ,maxrec=50000
                         ,type="C"
                         ,freq="A"
                         ,px="HS"
                         ,ps="now"
                         ,r
                         ,p
                         ,rg="all"
                         ,cc="TOTAL"
                         ,fmt="json"
)
{
  string<- paste(url
                 ,"max=",maxrec,"&" #maximum no. of records returned
                 ,"type=",type,"&" #type of trade (c=commodities)
                 ,"freq=",freq,"&" #frequency
                 ,"px=",px,"&" #classification
                 ,"ps=",ps,"&" #time period
                 ,"r=",r,"&" #reporting area
                 ,"p=",p,"&" #partner country
                 ,"rg=",rg,"&" #trade flow
                 ,"cc=",cc,"&" #classification code
                 ,"fmt=",fmt        #Format
                 ,sep = ""
  )
  
  if(fmt == "csv") {
    raw.data<- read.csv(string,header=TRUE)
    return(list(validation=NULL, data=raw.data))
  } else {
    if(fmt == "json" ) {
      raw.data<- fromJSON(file=string)
      data<- raw.data$dataset
      validation<- unlist(raw.data$validation, recursive=TRUE)
      ndata<- NULL
      if(length(data)> 0) {
        var.names<- names(data[[1]])
        data<- as.data.frame(t( sapply(data,rbind)))
        ndata<- NULL
        for(i in 1:ncol(data)){
          data[sapply(data[,i],is.null),i]<- NA
          ndata<- cbind(ndata, unlist(data[,i]))
        }
        ndata<- as.data.frame(ndata)
        colnames(ndata)<- var.names
      }
      return(list(validation=validation,data =ndata))
    }
  }
}

但是,有时它无法连接服务器,我需要几次运行代码才能开始工作。给定的解决方案在这里a>,使用 retry()函数,该函数会重新检索请求直到成功,这似乎很有吸引力。 但是,我在上面给出的代码中实现了此功能有一些困难。有人以前是否使用过它并知道如何重新描述它?

I use the UN Comtrade data API with R.

library(rjson)

get.Comtrade <- function(url="http://comtrade.un.org/api/get?"
                         ,maxrec=50000
                         ,type="C"
                         ,freq="A"
                         ,px="HS"
                         ,ps="now"
                         ,r
                         ,p
                         ,rg="all"
                         ,cc="TOTAL"
                         ,fmt="json"
)
{
  string<- paste(url
                 ,"max=",maxrec,"&" #maximum no. of records returned
                 ,"type=",type,"&" #type of trade (c=commodities)
                 ,"freq=",freq,"&" #frequency
                 ,"px=",px,"&" #classification
                 ,"ps=",ps,"&" #time period
                 ,"r=",r,"&" #reporting area
                 ,"p=",p,"&" #partner country
                 ,"rg=",rg,"&" #trade flow
                 ,"cc=",cc,"&" #classification code
                 ,"fmt=",fmt        #Format
                 ,sep = ""
  )
  
  if(fmt == "csv") {
    raw.data<- read.csv(string,header=TRUE)
    return(list(validation=NULL, data=raw.data))
  } else {
    if(fmt == "json" ) {
      raw.data<- fromJSON(file=string)
      data<- raw.data$dataset
      validation<- unlist(raw.data$validation, recursive=TRUE)
      ndata<- NULL
      if(length(data)> 0) {
        var.names<- names(data[[1]])
        data<- as.data.frame(t( sapply(data,rbind)))
        ndata<- NULL
        for(i in 1:ncol(data)){
          data[sapply(data[,i],is.null),i]<- NA
          ndata<- cbind(ndata, unlist(data[,i]))
        }
        ndata<- as.data.frame(ndata)
        colnames(ndata)<- var.names
      }
      return(list(validation=validation,data =ndata))
    }
  }
}

However, sometimes it fails to connect server and I need to run the code several times to start working. Solution given here, to use Retry() function, which retries a request until it succeeds, seems attractive.
However, I have some difficulties implementing this function in the code given above. has anybody used it before and knows how to recode it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骷髅 2025-01-27 20:25:30

使用 httr :: RETRY 的API调用看起来如下:

library(httr)
library(jsonlite)

res <- RETRY(
    verb = "GET",
    url = "http://comtrade.un.org/",
    path = "api/get",
    encode = "json",
    times = 3,
    query = list(
      max = 50000,
      type = "C",
      freq = "A",
      px = "HS",
      ps = "now",
      r = 842,
      p = "124,484",
      rg = "all",
      cc = "TOTAL",
      fmt = "json"
    )
  )

# alternativ: returns dataset as a `list`:
# parsed_content <- content(res, as = "parsed")    

# returns dataset as a `data.frame`:
json_content <- content(res, as = "text")
parsed_content <- parse_json(json_content, simplifyVector = TRUE)
parsed_content$validation
parsed_content$dataset

我建议使用 get.comTrade 使用 httr 函数:

get.Comtrade <- function(verb = "GET",
                         url = "http://comtrade.un.org/",
                         path = "api/get",
                         encode = "json",
                         times = 3,
                         max = 50000,
                         type = "C",
                         freq = "A",
                         px = "HS",
                         ps = "now",
                         r,
                         p,
                         rg = "all",
                         cc = "TOTAL",
                         fmt = "json") {
  res <- httr::RETRY(
    verb = verb,
    url = url,
    path = path,
    encode = encode,
    times = times,
    query = list(
      max = max,
      type = type,
      freq = freq,
      px = px,
      ps = ps,
      r = r,
      p = p,
      rg = rg,
      cc = cc,
      fmt = fmt
    )
  )
  jsonlite::parse_json(content(res, as = "text"), simplifyVector = TRUE)
}

s1 <- get.Comtrade(r = "842", p = "124,484", times = 5)
print(s1)

请参阅 this and this 有关 library(httr)

An API call using httr::RETRY could look like the following:

library(httr)
library(jsonlite)

res <- RETRY(
    verb = "GET",
    url = "http://comtrade.un.org/",
    path = "api/get",
    encode = "json",
    times = 3,
    query = list(
      max = 50000,
      type = "C",
      freq = "A",
      px = "HS",
      ps = "now",
      r = 842,
      p = "124,484",
      rg = "all",
      cc = "TOTAL",
      fmt = "json"
    )
  )

# alternativ: returns dataset as a `list`:
# parsed_content <- content(res, as = "parsed")    

# returns dataset as a `data.frame`:
json_content <- content(res, as = "text")
parsed_content <- parse_json(json_content, simplifyVector = TRUE)
parsed_content$validation
parsed_content$dataset

I'd suggest rewriting the get.Comtrade function using httr:

get.Comtrade <- function(verb = "GET",
                         url = "http://comtrade.un.org/",
                         path = "api/get",
                         encode = "json",
                         times = 3,
                         max = 50000,
                         type = "C",
                         freq = "A",
                         px = "HS",
                         ps = "now",
                         r,
                         p,
                         rg = "all",
                         cc = "TOTAL",
                         fmt = "json") {
  res <- httr::RETRY(
    verb = verb,
    url = url,
    path = path,
    encode = encode,
    times = times,
    query = list(
      max = max,
      type = type,
      freq = freq,
      px = px,
      ps = ps,
      r = r,
      p = p,
      rg = rg,
      cc = cc,
      fmt = fmt
    )
  )
  jsonlite::parse_json(content(res, as = "text"), simplifyVector = TRUE)
}

s1 <- get.Comtrade(r = "842", p = "124,484", times = 5)
print(s1)

result

Please see this and this for more information on library(httr).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文