python - 将httpie post请求转换为python requests库

标签 python python-requests httpie

我在使用 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/

相关文章:

python - Eventlet 或 gevent 或 Stackless + Twisted、Pylons、Django 和 SQL Alchemy

python - 格式:在字符串中使用大括号时出现 KeyError

python - 使用 Python 将 excel 文件上传到 SharePoint Online

android - python 请求中的 SSL 480 错误

python - 如何在 httpie 中设置重试次数?

python - 如何在 Python 中获取包含日志记录调用的类的名称?

python - 切换 python 打印的最佳方法是什么?

python - 限制 SSL 连接的带宽

python - 如何通过 HTTPie 使用空 json 数据发帖?

ssl - 如何在 HTTPie 中使用 CA(如 curl 的 --cacert)