簡體   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