【问题标题】:Translating curl to Python requests (post)将 curl 转换为 Python 请求(帖子)
【发布时间】:2019-07-31 17:26:16
【问题描述】:

我有一个如下格式的 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=$() 行。不太确定如何将其放入请求格式中。

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

【问题讨论】:

  • API 需要 JSON 数据,试试json 参数。
  • 还设置 h = {"Authorization: Bearer": "" }...它可能还需要对令牌进行一些编码...如果不尝试制作,我无法分辨我自己向您的 api 发出请求......所以它类似于 r = requests.post(url, headers=h, json=data)
  • 通过编码我的意思类似于这篇文章:stackoverflow.com/questions/18139093/… 所以可能是 {"Authorization": "Bearer" + base64.b64encode("") }
  • 你能显示响应头吗?

标签: python curl python-requests


【解决方案1】:

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

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

最终的payload应该如下:

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

【讨论】:

  • 感谢@Debendra!分离标头和 json 数据就可以了。
猜你喜欢
  • 1970-01-01
  • 2016-01-30
  • 2020-03-18
  • 2023-04-02
  • 2019-08-17
  • 2021-07-08
相关资源
最近更新 更多