简体   繁体   English

使用请求库卷曲到 Python

[英]Curl to Python using the Request library

I'm trying to translate Curl to Python, but I'm getting something wrong.我正在尝试将 Curl 转换为 Python,但出现错误。 Please help.请帮忙。

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"

PYTHON: PYTHON:

import requests
import json

def market_buy():
    header = {"Accept": "application/json",
               "Authorization": "Bearer <my auth code>"
             }
    data = {
    "order": {
        "units": "100",
        "instrument": "EUR_USD",
        "timeInForce": "FOK",
        "type": "MARKET",
        "positionFill": "DEFAULT"
      }
    }
    url = "https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders"
    r = requests.post(url, data=data, headers=header)    
    print(r.text)
market_buy()

Error Message:错误信息:

{"errorMessage":"Insufficient authorization to perform request."}

I've double-checked my credentials.我已经仔细检查了我的凭据。 I'm thinking something is wrong with the code.我在想代码有问题。

A direct translation from cURL to Python requests would be this:从 cURL 到 Python 请求的直接转换是这样的:

from requests import post

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer <AUTHENTICATION TOKEN>",
}

data = {
    "order": {
        "units": "100",
        "instrument": "EUR_USD",
        "timeInForce": "FOK",
        "type": "MARKET",
        "positionFill": "DEFAULT",
    }
}

post(
    "https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders",
    headers=headers,
    data=data,
)

I guess you are missing the SSL cert verification and basic authentication .我猜您缺少SSL cert verificationbasic authentication

You can turn off SSL cert verification with the verify flag, and use basic authentication by specifying auth.您可以使用 verify 标志关闭 SSL 证书验证,并通过指定 auth 使用基本身份验证。

from requests.auth import HTTPBasicAuth
import requests
import json

def market_buy():
    header = {"Accept": "application/json",
               "Authorization": "Bearer <my auth code>"
             }
    data = {
    "order": {
        "units": "100",
        "instrument": "EUR_USD",
        "timeInForce": "FOK",
        "type": "MARKET",
        "positionFill": "DEFAULT"
      }
    }
    url = "https://api-fxtrade.oanda.com/v3/accounts/<myaccount>/orders"
    r = requests.post(url, data=data, headers=header, auth=HTTPBasicAuth('admin', 'admin'), verify=False)    
    print(r.text)
market_buy()

I guess the above should work.我想以上应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM