gpt4 book ai didi

python - 将curl 转换为Python 请求(post)

转载 作者:行者123 更新时间:2023-12-01 08:13:38 27 4
gpt4 key购买 nike

我有一个以下格式的curl请求

body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)

curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"

我希望得到您的帮助,将其转换为 requests.post 格式。

这是我目前所拥有的,但似乎不起作用:

order_data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
},
'Authorization': 'Bearer '+<AUTHENTICATION TOKEN>
}

requests.post('https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders', data = order_data)

我已将 ACCOUNT 和 AUTHENTICATION TOKEN 替换为实际字符串。

我感到困惑的部分是 body=$() 行。不太确定如何将其适合请求格式。

希望得到您的帮助。谢谢。

最佳答案

Authorization 应作为 header 传递,Content-Type 必须为 'application/json',有效负载必须为 json 编码。

从 Requests 版本 2.4.2 及更高版本开始,您也可以在调用中使用“json”参数,这样会更简单。

最终的有效负载应如下所示:

order_data = {
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
headers = 'Authorization': 'Bearer <AUTHENTICATION TOKEN>'

requests.post('https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders', headers=headers, json=order_data)

Using the json parameter in the request will change the Content-Type in the header to application/json.

此处的文档:http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests

关于python - 将curl 转换为Python 请求(post),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55084229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com