Python Forum

Full Version: TypeError: must be str, not bytes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hi !

Error in this code:

Traceback (most recent call last):
File "C:/Cloud/Cripto/3.py", line 53, in <module>
print (api_query("GetBalance"))
File "C:/Cloud/Cripto/3.py", line 34, in api_query
signature = API_KEY + "POST" + urllib.parse.quote_plus( url ).lower() + nonce + requestContentBase64String
TypeError: must be str, not bytes

Please help, code below.
Thank you!



import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'ac85417173...abdf98138e...02'
API_SECRET = 'KY9R6bgPfQeDr2kV...rwm4aoGk0EvQwU...eduafbsk'


def api_query( method, req = None ):
if not req:
req = {}
print ("def api_query( method = " + method + ", req = " + str( req ) + " ):")
time.sleep( 1 )
public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
if method in public_set:
url = "https://www.cryptopia.co.nz/api/" + method
if req:
for param in req:
url += '/' + str( param )
r = requests.get( url )
elif method in private_set:
url = "https://www.cryptopia.co.nz/Api/" + method
nonce = str( int( time.time() ) )
post_data = json.dumps( req );
m = hashlib.md5()
m.update(post_data.encode('utf-8'))
requestContentBase64String = base64.b64encode(m.digest())
signature = API_KEY + "POST" + urllib.parse.quote_plus( url ).lower() + nonce + requestContentBase64String
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
r = requests.post( url, data = post_data, headers = headers )
response = r.text
print ("( Response ): " + response)
return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
print (api_query("GetMarket", [ 100, 6 ] ))
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice ":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error ":None}

# Private:
print (api_query("GetBalance"))

# +
# print api_query("GetBalance", {'CurrencyId':2} )
import time
import hmac
import urllib
import requests
import hashlib
import base64
import sys
import json

API_KEY = 'ac85417173...abdf98138e...02'
API_SECRET = 'KY9R6bgPfQeDr2kV...rwm4aoGk0EvQwU...eduafbsk'


def api_query( method, req = None ):
 if not req:
         req = {}
 print ("def api_query( method = " + method + ", req = " + str( req ) + " ):")
 time.sleep( 1 )
 public_set = set([ "GetCurrencies", "GetTradePairs", "GetMarkets", "GetMarket", "GetMarketHistory", "GetMarketOrders" ])
 private_set = set([ "GetBalance", "GetDepositAddress", "GetOpenOrders", "GetTradeHistory", "GetTransactions", "SubmitTrade", "CancelTrade", "SubmitTip" ])
 if method in public_set:
         url = "https://www.cryptopia.co.nz/api/" + method
         if req:
             for param in req:
                 url += '/' + str( param )
         r = requests.get( url )
 elif method in private_set:
         url = "https://www.cryptopia.co.nz/Api/" + method
         nonce = str( int( time.time() ) )
         post_data = json.dumps( req );
         m = hashlib.md5()
         m.update(post_data.encode('utf-8'))
         requestContentBase64String = base64.b64encode(m.digest())
         signature = API_KEY + "POST" + urllib.parse.quote_plus( url ).lower() + nonce + requestContentBase64String
         hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
         header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
         headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
         r = requests.post( url, data = post_data, headers = headers )
 response = r.text
 print ("( Response ): " + response)
 return response.replace("false","False").replace("true","True").replace('":null','":None' )


# Public:
# +
# print api_query("GetCurrencies")

# +
#print (api_query("GetMarket", [ 101, 6 ] ))
# {"Success":True,"Message":None,"Data":{"TradePairId":100,"Label":"DOT/BTC","AskPrice":0.00000020,"BidPrice":0.00000019,"Low":0.00000019,"High":0.00000021,"Volume":1263556.65136394,"LastPrice":0.00000019,"LastVolume":774.83684404,"BuyVolume":50896673.08961847,"SellVolume":33046510.52562918,"Change":0.0},"Error":None}

# Private:
print (api_query("GetBalance"))

# +
# print api_query("GetBalance", {'CurrencyId':2} )
base64.b64encode(m.digest()) returns bytes. You have to convert it to string.
(Jan-06-2018, 04:22 PM)wavic Wrote: [ -> ]base64.b64encode(m.digest()) returns bytes. You have to convert it to string.

Thank You very much!
And how to do it ?
line 33:
requestContentBase64String = base64.b64encode(m.digest()).decode('utf-8')
(Jan-06-2018, 04:33 PM)wavic Wrote: [ -> ]line 33:
requestContentBase64String = base64.b64encode(m.digest()).decode('utf-8')
Thank You very much!
Now a new error

Traceback (most recent call last):
File "C:/Cloud/Cripto/3.py", line 53, in <module>
print (api_query("GetBalance"))
File "C:/Cloud/Cripto/3.py", line 35, in api_query
hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest())
File "C:\Users\Сергей\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
There is something with the API_SECRET value. See the altchars parameter.
(Jan-06-2018, 05:16 PM)wavic Wrote: [ -> ]There is something with the API_SECRET value. See the altchars parameter.

Thank you very much!
I'll figure it out.
Need to organize the query API to place the order. Trying to use existing code, as it is not out yet.
Consider that base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest()) will return bytes again. So you have to convert it to string. As before
(Jan-06-2018, 06:16 PM)wavic Wrote: [ -> ]Consider that base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest()) will return bytes again. So you have to convert it to string. As before

Thank you very much!
Now you will understand and change code.

(Jan-06-2018, 06:25 PM)Zhsv Wrote: [ -> ]
(Jan-06-2018, 06:16 PM)wavic Wrote: [ -> ]Consider that base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest()) will return bytes again. So you have to convert it to string. As before

Thank you very much!
Now you will understand and change code.

So changed. The error persists

 elif method in private_set:
         url = "https://www.cryptopia.co.nz/Api/" + method
         nonce = str( int( time.time() ) )
         post_data = json.dumps( req );
         m = hashlib.md5()
         m.update(post_data.encode('utf-8'))
         requestContentBase64String = base64.b64encode(m.digest()).decode('utf-8')
         signature = API_KEY + "POST" + urllib.parse.quote_plus( url ).lower() + nonce + requestContentBase64String
         hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest()).decode('utf-8')
         header_value = "amx " + API_KEY + ":" + hmacsignature + ":" + nonce
         headers = { 'Authorization': header_value, 'Content-Type':'application/json; charset=utf-8' }
         r = requests.post( url, data = post_data, headers = headers )
 response = r.text
Error:
def api_query( method = GetBalance, req = {} ): Traceback (most recent call last): File "C:/Cloud/Cripto/3.py", line 53, in <module> print (api_query("GetBalance")) File "C:/Cloud/Cripto/3.py", line 35, in api_query hmacsignature = base64.b64encode(hmac.new(base64.b64decode( API_SECRET ), signature, hashlib.sha256).digest()).decode('utf-8') File "C:\Users\Сергей\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Incorrect padding >>>
Pages: 1 2