我在使用 htppie 将 post 请求转换为 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 服务器错误(客户端错误):第 1 行第 1 列的预期值
。
无论服务器错误是什么(可能是特定于服务器的),这至少意味着两个请求显然不完全相同。
那么我该如何将此 httpie 请求转换为使用 pythons requests 库(或任何其他与此相关的 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。
关于python - 将httpie post请求转换为python requests库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66537823/