Python 请求库获取 oauth 令牌

Python requests library for oauth token

所以我按照指南从 https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/ 获取 OAUTH 令牌 我尝试对上述等效代码执行 python 请求库,但我从服务器收到了 400 响应。我可以知道我哪里错了吗?

import requests
import json
import clientidandsecret


headers ={"Authorization": "Basic " + clientidandsecret.C_ID +":" +clientidandsecret.C_SECRET}
form = {"form":{"grant_type" :"client_credentials"}, "json":"true"}
result = requests.post("https://accounts.spotify.com/api/token", headers=headers, data=form)
print(result)

你的变量形式是一个字典,如果你想在请求中使用参数数据,它需要是一个字符串,这将修复它:

import json
...
result = requests.post(url, headers=headers, data=json.dumps(form))

甚至更好:

result = requests.post(url, headers=headers, json=form)