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

标签 python curl python-requests

我有一个以下格式的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/

相关文章:

c - 对符号 'CERT_GetDefaultCertDB@@NSS_3.2' 的 undefined reference

PHP 启动 : Unable to load dynamic library php_curl. dll

php - 通过 PHP Curl PUT 上传文件

python - 如何在python脚本中发送post请求正文

python - Keras 2.2.4 如何从 Keras 1.x.x 复制 merge()

Python - smtp 需要身份验证

python - 模块未找到错误 : No module named 'urllib3.exceptions' ; 'urllib3' is not a package

python-3.x - 如果服务器没有在python3中以两种方式SSL身份验证请求客户端证书,如何停止握手和数据共享?

python - 检查进程是否在 Windows 上运行?

python - 将标签映射到 tf.unique_with_counts() 之后的计数