有没有一种方法可以使用python请求模块形成批量请求?我想在一个POST请求中发送多个同类的http API请求



有没有一种方法可以使用python请求模块形成批量请求?我想在一个POST请求中发送多个同类的http API请求。我正在尝试使用GCP文档https://cloud.google.com/dns/docs/reference/batch?hl=en_US&amp_ga=2.138235123.-2126794010.1660759555在单个POST请求中创建多个DNS记录。有人能提供一个简单的例子来说明如何使用python请求模块来实现这一点吗?

以下是示例POST请求的样子:

POST /batch/farm/v1 HTTP/1.1
Authorization: Bearer your_auth_token
Host: www.googleapis.com
Content-Type: multipart/mixed; boundary=batch_foobarbaz
Content-Length: total_content_length
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item1:12930812@barnyard.example.com>
GET /farm/v1/animals/pony
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item2:12930812@barnyard.example.com>
PUT /farm/v1/animals/sheep
Content-Type: application/json
Content-Length: part_content_length
If-Match: "etag/sheep"
{
"animalName": "sheep",
"animalAge": "5"
"peltColor": "green",
}
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item3:12930812@barnyard.example.com>
GET /farm/v1/animals
If-None-Match: "etag/animals"
--batch_foobarbaz--

基本上;这里的主要意图是不使用导致速率限制节流的多个http请求来重载远程API,而是使用批处理的http请求,使得远程API仅获得以部分形式嵌入多个请求的单个批处理请求。

否。HTTP不是那样工作的。您可以使用线程同时发送多个请求,但不能通过单个请求发送多个POST。

根据文档,单个批处理HTTP请求应该放在请求的主体中。您可以尝试手动构建请求。像这样:

import requests
body = """
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item1:12930812@barnyard.example.com>
GET /farm/v1/animals/pony
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item2:12930812@barnyard.example.com>
PUT /farm/v1/animals/sheep
Content-Type: application/json
Content-Length: part_content_length
If-Match: "etag/sheep"
{
"animalName": "sheep",
"animalAge": "5"
"peltColor": "green",
}
--batch_foobarbaz
Content-Type: application/http
Content-ID: <item3:12930812@barnyard.example.com>
GET /farm/v1/animals
If-None-Match: "etag/animals"
--batch_foobarbaz--
"""
response = requests.post(
"https://www.googleapis.com/batch/API/VERSION/batch/form/v1",
data=body,
headers={
'Authorization': 'Bearer your_auth_token',
'Host': 'www.googleapis.com',
'Content-Type': 'multipart/mixed; boundary=batch_foobarbaz'
}
)

当然,您必须手动构建单个请求:

Content-Type: application/http
Content-ID: <item1:12930812@barnyard.example.com>
GET /farm/v1/animals/pony

除非你能找到一个可以根据HTTP/1.1 RFC构建HTTP请求的库。我脑子里想不出一个。

最新更新