2017-11-11 79 views
0

我試圖運行一個類似於在這個問題上的代碼:How do I sign a POST request using HMAC-SHA512 and the Python requests library?Python的請求,沒有屬性「體」

我有以下代碼:

import requests 
import hmac 
import hashlib 
from itertools import count 
import time 

headers = { 'nonce': '', 
     'Key' : 'myKey', 
     'Sign': '',} 
payload = { 'command': 'returnCompleteBalances', 
      'account': 'all'} 
secret = 'mySecret' 

NONCE_COUNTER = count(int(time.time() * 1000)) 
headers['nonce'] = next(NONCE_COUNTER) 

request = requests.Request(
    'POST', 'https://poloniex.com/tradingApi', 
    params=payload, headers=headers) 
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512) 
request.headers['Sign'] = signature.hexdigest() 

with requests.Session() as session: 
    response = session.send(request) 

以下行:

signature = hmac.new(secret, request.body, digestmod=hashlib.sha512) 

拋出這個錯誤:'請求' 對象有沒有屬性 '身體'

+0

嘗試:request.content – Gui

+0

,我收到了類似的錯誤:「請求」對象有沒有屬性「內容」 –

+1

嘗試request.text –

回答

1

你的源代碼有幾個問題:

  1. 因爲你不能使用參數params POST方法,但你需要的參數data
  2. 如前所述,您需要使用.prepare()方法。
  3. 參數nonce還需要在​​中指定,而不是在headers中。

這應該工作:

import requests 
import hmac 
import hashlib 
from itertools import count 
import time 

NONCE_COUNTER = count(int(time.time() * 1000)) 

headers = { 'Key' : 'myKey', 
      'Sign': '',} 

payload = { 'nonce': next(NONCE_COUNTER), 
      'command': 'returnCompleteBalances', 
      'account': 'all'} 

secret = 'mySecret' 


request = requests.Request(
    'POST', 'https://poloniex.com/tradingApi', 
    data=payload, headers=headers).prepare() 
signature = hmac.new(secret, request.body, digestmod=hashlib.sha512) 
request.headers['Sign'] = signature.hexdigest() 


with requests.Session() as session: 
    response = session.send(request) 
相關問題