簡體   English   中英

將 httpie post 請求轉換為 python 請求庫

[英]Convert httpie post request to python requests library

我很難將使用 htppie 的發布請求轉換為 python requests.post。 這個問題一般是關於如何進行這樣的轉換,但我會以我正在做的具體請求為例。

所以我有以下使用httpie的post請求,它工作正常:

http post https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet query='{ indexers {
                id
               }
}'

但是,當嘗試使用 pythons requests 庫發送相同的請求時,我嘗試了以下操作:

import requests

url = 'https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet'

query = """'{ indexers {
                id
                }
}'"""

print(requests.post(url, data = query).text)

這會導致服務器錯誤(我嘗試了許多版本,以及為數據變量發送字典,它們都給出了相同的錯誤)。 服務器錯誤為GraphQL server error (client error): expected value at line 1 column 1

不管服務器錯誤是什么(可能是特定於服務器的),這至少意味着這兩個請求顯然不完全相同。

那么我將如何 go 將這個 httpie 請求轉換為使用 pythons 請求庫(或任何其他 python 庫)?

要傳遞請求有效負載,您需要將 json 作為字符串傳遞(我使用json.dumps()進行轉換)。 要將正文作為表單數據傳遞,只需傳遞 dict。

import json
import requests

url = 'https://api.thegraph.com/subgraphs/name/graphprotocol/graph-network-mainnet'

payload=json.dumps({'query': '{indexers {id}}'})
headers = {
  'Content-Type': 'application/json',
}

response = requests.post(url, headers=headers, data=payload)

筆記。 我建議您嘗試在 Postman 中提出此請求,然后您可以在 Postman 中將代碼轉換為 Python。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM