这是一个玩具,不可复制的例子,因为我不能分享原件.我认为这是有责任的,可能会对其他人有所帮助.从其他像this和this这样的SO帖子来看,我的理解是,给定一些参数词典d
,它们是等价的:
requests.post(url, data=json.dumps(d))
requests.post(url, json=d)
令牌端点的参数在文档中定义如下:
- URL:{{base_url}}/Token
- 参数
- Grand_type=\\密码/LI>
- 用户名=__用户名/LI>
- Password=\\Password/LI>
- 范围={"Account":"__Account+","Tenant":"__Tenant抯/Li>
我从这个开始,从.env文件加载变量:
resp = requests.post(f'{base_url}/token',
json={'grant_type': 'password', 'username': uname, 'password': pwd,
'scope': {'account': account, 'tenant': tenant}})
resp.text
# '{"error":"unsupported_grant_type"}'
我try 更改为data参数,得到了一个更合理的错误:
resp = requests.post(f'{base_url}/token',
data={'grant_type': 'password', 'username': uname, 'password': pwd,
'scope': {'account': account, 'tenant': tenant}})
resp.text
# '{"error":"invalid_grant","error_description":"{\\"ErrorMessage\\":\\"Error trying to Login - User [username] Account [] Unexpected character encountered while parsing value: a.
我try 了其他一些方法,比如用引号将arg括起来(例如{'account': f"{account}"}
),但没有成功,最终用这个"混合"方法成功了:
resp = requests.post(f'{base_url}/token',
data={'grant_type': 'password', 'username': uname, 'password': pwd,
'scope': json.dumps({'account': account, 'tenant': tenant})})
我的问题:
- 这种细微差别是"真实的"还是直接阅读相关问题?也就是说,看起来either使用
data=json.dumps(d)
或json=d
,但我还没有找到混合这两者的答案(将整个data
arg包装在json.dumps()
中打破了我正在工作的最终版本) - 作为API/网络领域的新手,我能从上面列出的文档论证中看出这一点吗,或者试错是发现这一点的唯一方法吗?
- 给出我的最终解决方案,有没有更好/更正确的方式来传递这些参数?