繁体   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