使用R查询服务器,基于Python示例。

huangapple go评论108阅读模式
英文:

Querying a server with R based on a Python example

问题

我正在尝试将以下的Python脚本转换成R

library(httr)
library(jsonlite)

get_telraam_data <- function(id = "9000001463",
                           time_start = "2022-10-01 00:00:00Z",
                           time_end = "2022-10-02 00:00:00Z",
                           level = "segments",
                           format = "per-hour",
                           token = "***My_API-Key***") {
  url <- "https://telraam-api.net/v1/reports/traffic"
  
  body <- list(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format
  )
  
  headers <- add_headers("X-Api-Key" = token)
  
  response <- POST(url, body = body, headers = headers, encode = "json")
  
  stop_for_status(response)
  
  json <- content(response, type = "text", encoding = "UTF-8") %>%
    fromJSON(flatten = TRUE)
  
  dataframe <- as.data.frame(json$report)
  
  write.csv(dataframe, file = "test.csv")
}

其中的My_API-Key代表我的 API 密钥,我无法提供。

我使用了以下代码,但查询似乎不起作用:

get_telraam_data()

我哪里出错了?
body 是否应该作为 query

英文:

I am trying to convert the following Python script in R:

import pandas as pd
import requests
import json
url = &quot;https://telraam-api.net/v1/reports/traffic&quot;
body = {
    &quot;id&quot;:&quot;9000001463&quot;,
    &quot;time_start&quot;:&quot;2022-10-01 00:00:00Z&quot;,
    &quot;time_end&quot;:&quot;2022-10-02 00:00:00Z&quot;,
    &quot;level&quot;:&quot;segments&quot;,
    &quot;format&quot;:&quot;per-hour&quot;
}
headers = {
  &#39;X-Api-Key&#39;: &#39;***My_API-Key***&#39;
}
payload = str(body)
response = requests.request(&quot;POST&quot;, url, headers=headers, data=payload)
json = response.json()
dataframe = pd.DataFrame(json[&#39;report&#39;])
dataframe.to_csv(&#39;test.csv&#39;)

where My_API-Key stands for my API key which I cannot communicate.

I used the following:

get_telraam_data &lt;- function(id = &quot;9000001463&quot;,
                       time_start = &quot;2022-10-01 00:00:00Z&quot;,
                       time_end = &quot;2022-10-02 00:00:00Z&quot;,
                       level = &quot;segments&quot;,
                       format = &quot;per-hour&quot;,
                       token = &quot;***My_API-Key***&quot;) {
  GET(
    url = sprintf(&quot;https://telraam-api.net/v1&quot;),
    query = list(
      id = id,
      time_start = time_start,
      time_end = time_end,
      level = level,
      format = format
    ),
    content_type_json(),
    add_headers(&quot;X-Api-Key&quot; = token)
  ) -&gt; res

  stop_for_status(res)

  content(res, as=&quot;text&quot;, encoding=&quot;UTF-8&quot;) %&gt;%
    fromJSON(flatten=TRUE) %&gt;%
    as_tibble() %&gt;%
    readr::type_convert()
}

but the query does not seem to work.

Where did I make an error?
Is body a query?

答案1

得分: 1

requests.request("POST", ...) 是一个 POST 调用,而 httr 的示例是使用 GET。您可以通过调用一些测试服务来比较请求/响应,例如 http://httpbin.org/。或者只需在您自己的计算机上打开一个套接字,以查看请求的差异。使用 httr,可以这样做:

library(httr)

id         <- "9000001463"
time_start <- "2022-10-01 00:00:00Z"
time_end   <- "2022-10-02 00:00:00Z"
level      <- "segments"
format     <- "per-hour"
token      <- "***My_API-Key***"

api_endpoint <- "https://httpbin.org/post"
# 或者只需在您自己的主机上运行netcat以检查请求:
# nc -l 1234
#api_endpoint <- "http://localhost:1234"

POST(
  url = api_endpoint,
  body = list(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format
  ),
  encode = "json",
  content_type_json(),
  add_headers("X-Api-Key" = token)
)
#> Response [https://httpbin.org/post]
#>   Date: 2023-05-28 19:15
#>   Status: 200
#>   Content-Type: application/json
#>   Size: 851 B
#> {
#>   "args": {}, 
#>   "data": "{\"id\":\"9000001463\",\"time_start\":\"2022-10-01 00:00:00Z\",\"t...
#>   "files": {}, 
#>   "form": {}, 
#>   "headers": {
#>     "Accept": "application/json, text/xml, application/xml, */*", 
#>     "Accept-Encoding": "deflate, gzip", 
#>     "Content-Length": "128", 
#>     "Content-Type": "application/json", 
#>     ...
#> }

虽然我个人会使用 httr2

library(dplyr)
library(httr2)
response <-  request(api_endpoint) %>%
  req_headers("X-Api-Key" = token) %>%
  req_body_json(list(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format)) %>%
  # 要检查请求而不实际发送它:
  # req_dry_run()
  req_perform(verbosity = 2) %>%
  resp_body_json(simplifyVector = TRUE) 
#> -> POST /post HTTP/1.1
#> -> Host: httpbin.org
#> -> User-Agent: httr2/0.2.2 r-curl/5.0.0 libcurl/7.84.0
#> -> Accept: */*
#> -> Accept-Encoding: deflate, gzip
#> -> X-Api-Key: ***My_API-Key***
#> -> Content-Type: application/json
#> -> Content-Length: 128
#> -> 
#> >> {"id":"9000001463","time_start":"2022-10-01 00:00:00Z","time_end":"2022-10-02 00:00:00Z","level":"segments","format":"per-hour"}
#> <- HTTP/1.1 200 OK
#> <- Date: Sun, 28 May 2023 19:15:26 GMT
#> <- Content-Type: application/json
#> <- Content-Length: 807
#> <- Connection: keep-alive
#> <- Server: gunicorn/19.9.0
#> <- Access-Control-Allow-Origin: *
#> <- Access-Control-Allow-Credentials: true
#> <- 
#> << {
#> <<   "args": {}, 
#> <<   "data": "{\"id\":\"9000001463\",\"time_start\":\"2022-10-01 00:00:00Z\",\"time_end\":\"2022-10-02 00:00:00Z\",\"level\":\"segments\",\"format\":\"per-hour\"}", 
#> <<   "files": {}, 
#> <<   "form": {}, 
#> <<   "headers": {
#> <<     "Accept": "*/*", 
#> <<     "Accept-Encoding": "deflate, gzip", 
#> <<     "Content-Length": "128", 
#> <<     "Content-Type": "application/json", 
#> <<     "Host": "httpbin.org", 
#> <<     "User-Agent": "httr2/0.2.2 r-curl/5.0.0 libcurl/7.84.0", 
#> <<     "X-Amzn-Trace-Id": "Root=1-6473a84e-5ed51b7c52cac4ce2a19f855", 
#> <<     "X-Api-Key": "***My_API-Key***"
#> <<   }, 
#> <<   "json": {
#> <<     "format": "per-hour", 
#> <<     "id": "9000001463", 
#> <<     "level": "segments", 
#> <<     "time_end": "2022-10-02 00:00:00Z", 
#> <<     "time_start": "2022-10-01 00:00:00Z"
#> <<   }, 
#> <<   "origin": "91.101.104.191", 
#> <<   "url": "https://httpbin.org/post"
#> << }

创建于2023年05月28日,使用reprex v2.0.2

英文:

requests.request(&quot;POST&quot;, ...) is a POST call while httr example is using GET. You can compare requests / responses by making calls to some testing service, e.g. http://httpbin.org/ . Or just open up a socket on your own machine to see how requests differ. With httr, this should do:

library(httr)

id         &lt;- &quot;9000001463&quot;
time_start &lt;- &quot;2022-10-01 00:00:00Z&quot;
time_end   &lt;- &quot;2022-10-02 00:00:00Z&quot;
level      &lt;- &quot;segments&quot;
format     &lt;- &quot;per-hour&quot;
token      &lt;- &quot;***My_API-Key***&quot;

api_endpoint &lt;- &quot;https://httpbin.org/post&quot;
# or just run netcat on your own host to check the request:
# nc -l 1234
#api_endpoint &lt;- &quot;http://localhost:1234&quot;

POST(
  url = api_endpoint,
  body = list(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format
  ),
  encode = &quot;json&quot;,
  content_type_json(),
  add_headers(&quot;X-Api-Key&quot; = token)
)
#&gt; Response [https://httpbin.org/post]
#&gt;   Date: 2023-05-28 19:15
#&gt;   Status: 200
#&gt;   Content-Type: application/json
#&gt;   Size: 851 B
#&gt; {
#&gt;   &quot;args&quot;: {}, 
#&gt;   &quot;data&quot;: &quot;{\&quot;id\&quot;:\&quot;9000001463\&quot;,\&quot;time_start\&quot;:\&quot;2022-10-01 00:00:00Z\&quot;,\&quot;t...
#&gt;   &quot;files&quot;: {}, 
#&gt;   &quot;form&quot;: {}, 
#&gt;   &quot;headers&quot;: {
#&gt;     &quot;Accept&quot;: &quot;application/json, text/xml, application/xml, */*&quot;, 
#&gt;     &quot;Accept-Encoding&quot;: &quot;deflate, gzip&quot;, 
#&gt;     &quot;Content-Length&quot;: &quot;128&quot;, 
#&gt;     &quot;Content-Type&quot;: &quot;application/json&quot;, 
#&gt; ...

Though I'd personally use httr2:

library(dplyr)
library(httr2)
response &lt;-  request(api_endpoint) %&gt;% 
  req_headers(&quot;X-Api-Key&quot; = token) %&gt;% 
  req_body_json(list(
    id = id,
    time_start = time_start,
    time_end = time_end,
    level = level,
    format = format)) %&gt;% 
  # to check request without actually sending it:
  # req_dry_run()
  req_perform(verbosity = 2) %&gt;% 
  resp_body_json(simplifyVector = TRUE) 
#&gt; -&gt; POST /post HTTP/1.1
#&gt; -&gt; Host: httpbin.org
#&gt; -&gt; User-Agent: httr2/0.2.2 r-curl/5.0.0 libcurl/7.84.0
#&gt; -&gt; Accept: */*
#&gt; -&gt; Accept-Encoding: deflate, gzip
#&gt; -&gt; X-Api-Key: ***My_API-Key***
#&gt; -&gt; Content-Type: application/json
#&gt; -&gt; Content-Length: 128
#&gt; -&gt; 
#&gt; &gt;&gt; {&quot;id&quot;:&quot;9000001463&quot;,&quot;time_start&quot;:&quot;2022-10-01 00:00:00Z&quot;,&quot;time_end&quot;:&quot;2022-10-02 00:00:00Z&quot;,&quot;level&quot;:&quot;segments&quot;,&quot;format&quot;:&quot;per-hour&quot;}
#&gt; &lt;- HTTP/1.1 200 OK
#&gt; &lt;- Date: Sun, 28 May 2023 19:15:26 GMT
#&gt; &lt;- Content-Type: application/json
#&gt; &lt;- Content-Length: 807
#&gt; &lt;- Connection: keep-alive
#&gt; &lt;- Server: gunicorn/19.9.0
#&gt; &lt;- Access-Control-Allow-Origin: *
#&gt; &lt;- Access-Control-Allow-Credentials: true
#&gt; &lt;- 
#&gt; &lt;&lt; {
#&gt; &lt;&lt;   &quot;args&quot;: {}, 
#&gt; &lt;&lt;   &quot;data&quot;: &quot;{\&quot;id\&quot;:\&quot;9000001463\&quot;,\&quot;time_start\&quot;:\&quot;2022-10-01 00:00:00Z\&quot;,\&quot;time_end\&quot;:\&quot;2022-10-02 00:00:00Z\&quot;,\&quot;level\&quot;:\&quot;segments\&quot;,\&quot;format\&quot;:\&quot;per-hour\&quot;}&quot;, 
#&gt; &lt;&lt;   &quot;files&quot;: {}, 
#&gt; &lt;&lt;   &quot;form&quot;: {}, 
#&gt; &lt;&lt;   &quot;headers&quot;: {
#&gt; &lt;&lt;     &quot;Accept&quot;: &quot;*/*&quot;, 
#&gt; &lt;&lt;     &quot;Accept-Encoding&quot;: &quot;deflate, gzip&quot;, 
#&gt; &lt;&lt;     &quot;Content-Length&quot;: &quot;128&quot;, 
#&gt; &lt;&lt;     &quot;Content-Type&quot;: &quot;application/json&quot;, 
#&gt; &lt;&lt;     &quot;Host&quot;: &quot;httpbin.org&quot;, 
#&gt; &lt;&lt;     &quot;User-Agent&quot;: &quot;httr2/0.2.2 r-curl/5.0.0 libcurl/7.84.0&quot;, 
#&gt; &lt;&lt;     &quot;X-Amzn-Trace-Id&quot;: &quot;Root=1-6473a84e-5ed51b7c52cac4ce2a19f855&quot;, 
#&gt; &lt;&lt;     &quot;X-Api-Key&quot;: &quot;***My_API-Key***&quot;
#&gt; &lt;&lt;   }, 
#&gt; &lt;&lt;   &quot;json&quot;: {
#&gt; &lt;&lt;     &quot;format&quot;: &quot;per-hour&quot;, 
#&gt; &lt;&lt;     &quot;id&quot;: &quot;9000001463&quot;, 
#&gt; &lt;&lt;     &quot;level&quot;: &quot;segments&quot;, 
#&gt; &lt;&lt;     &quot;time_end&quot;: &quot;2022-10-02 00:00:00Z&quot;, 
#&gt; &lt;&lt;     &quot;time_start&quot;: &quot;2022-10-01 00:00:00Z&quot;
#&gt; &lt;&lt;   }, 
#&gt; &lt;&lt;   &quot;origin&quot;: &quot;91.101.104.191&quot;, 
#&gt; &lt;&lt;   &quot;url&quot;: &quot;https://httpbin.org/post&quot;
#&gt; &lt;&lt; }

<sup>Created on 2023-05-28 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年5月29日 01:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352764.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定