对 Poloniex 的请求 API

Requests for Poloniex API

我正在尝试使用 Poloniex API。我尝试通过交易 API 方法获得余额。我试着用 requests 库来做,像这样:

import requests
import hmac
import hashlib
import time
import urllib

def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    polo_request = requests.post('https://poloniex.com/tradingApi', data=post_data, headers=headers, timeout=20)
    polo_request = polo_request.json()
    print('Request: {0}'.format(polo_request))
    return polo_request

使用此代码时,我总是收到错误消息:"Request: {'error': 'Invalid command.'}"。我做错了什么?

来自下面returns的另一边代码数据没有任何问题!请看这个:

import requests
import hmac
import hashlib
import json
import time
import urllib

def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    req = urllib.request.Request('https://poloniex.com/tradingApi', data=post_data, headers=headers)
    res = urllib.request.urlopen(req, timeout=20)
    Ret_data = json.loads(res.read().decode('utf-8'))
    print('Request: {0}'.format(Ret_data))
    return Ret_data

我用的是Python3.6

最好让 requests 处理 post 数据,因为它会创建适当的 headers。除此之外,我没有发现您的代码有任何问题。

def setPrivateCommand(self):
    poloniex_data = {'command': 'returnBalances', 'nonce': int(time.time() * 1000)}
    post_data = urllib.parse.urlencode(poloniex_data).encode()
    sig = hmac.new(
        str.encode(app.config['HMAC_KEYS']['Poloniex_Secret']), post_data, hashlib.sha512
    ).hexdigest()
    headers = {'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey']}
    polo_request = requests.post(
        'https://poloniex.com/tradingApi', data=poloniex_data, headers=headers, timeout=20
    )
    polo_request = polo_request.json()
    print('Request: {0}'.format(polo_request))
    return polo_request 

或者你可以在 headers 中指定 'Content-Type' 如果你想在 data 中有一个字符串,例如

headers = {
    'Sign': sig, 'Key': app.config['HMAC_KEYS']['Poloniex_APIKey'], 
    'Content-Type': 'application/x-www-form-urlencoded'
}
polo_request = requests.post(
    'http://httpbin.org/anything', data=post_data, headers=headers, timeout=20
)