【问题标题】:Converting from curl to python request.post从 curl 转换为 python request.post
【发布时间】:2019-08-05 11:55:39
【问题描述】:

我希望将当前的 curl 命令转换为 python 代码以请求 api 的访问令牌。

curl -X POST -H "Content-Type:application/json" -d '{"grantType":"client_credentials"}' [Access Token URL] 

我的尝试:

import requests

api_url_base = "https://api.example.com/api/"
headers ={'Content_Type':'application/json',
        'grandType': 'client_credentials'
        }

response = requests.post(headers=headers, "https://api.example.com/accesstokens")
if response.status_code == 200:
    print(json.loads(response.content.decode('utf-8')))
else:
    print(response.status_code)

预期输出: 应该在python中。

【问题讨论】:

  • 不行吗?如果有怎么办?
  • 这段代码有效吗?有什么问题?

标签: python curl


【解决方案1】:

您在那里发布的标题和正文数据不匹配,更不用说grandType 的拼写错误。

无论哪种方式,使用 Requests 发布 JSON 和解析 JSON 响应都非常简单:

response = requests.post(
    "https://api.example.com/accesstokens",
    json={"grantType": "client_credentials"},
)
response.raise_for_status()  # raise an exception for error statuses
data = response.json()
print(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2016-01-30
    相关资源
    最近更新 更多