繁体   English   中英

有没有办法使用 python requests 模块形成批处理请求? 我想在单个 POST 请求中发送多个同质 http API 请求

[英]Is there a way to form batched requests using python requests module ? I want to send multiple homogenous http API requests in a single POST request

有没有办法使用 python requests 模块形成批处理请求? 我想在单个 POST 请求中发送多个同质 http API 请求。 我正在尝试使用 GCP 文档https://cloud.google.com/dns/docs/reference/batch?hl=en_US&_ga=2.138235123.-2126794010.1660759555在单个 POSTZ 请求中创建多个 ZED5F2BDECBD4BD349D09412D1FF6 记录。 谁能提供一个简单的例子来说明如何使用 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--

基本上; the main intention here is to not overload the remote API with multiple http requests causing the rate limit throttling but instead use batched http requests so that the remote API gets only a single batched request embedded with multiple requests in the form of parts.

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

根据文档,单个批次 HTTP 请求应该是请求正文中的 go 。 您可以尝试手动构建请求。 像这样:

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 请求的库。 我想不出来一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM