将curl转换为Python请求(发布)

时间:2019-03-10 03:42:58

标签: python curl python-requests

我有以下格式的卷曲请求

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"

我希望您能将其转换为request.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 = $()行。不太确定如何使其适合请求格式。

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

1 个答案:

答案 0 :(得分:1)

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

从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)
  

在请求中使用json参数会将标头中的Content-Type更改为application/json

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