Python Forum
TypeError: must be str, not bytes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TypeError: must be str, not bytes
#1
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} )
Reply
#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} )
Reply
#3
base64.b64encode(m.digest()) returns bytes. You have to convert it to string.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
(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 ?
Reply
#5
line 33:
requestContentBase64String = base64.b64encode(m.digest()).decode('utf-8')
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#6
(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
Reply
#7
There is something with the API_SECRET value. See the altchars parameter.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#8
(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.
Reply
#9
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
(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 >>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  TypeError: a bytes-like object is required ZeroX 13 4,159 Jan-07-2023, 07:02 PM
Last Post: deanhystad
  TypeError: a bytes-like object is required, not 'str' - Help Please. IanJ 3 4,821 Aug-29-2022, 05:53 PM
Last Post: deanhystad
  python 3: TypeError: a bytes-like object is required, not 'str' wardancer84 3 6,512 Jul-09-2021, 05:55 PM
Last Post: deanhystad
  TypeError: int() argument must be a string, a bytes-like object or a number, not 'Non Anldra12 2 5,216 May-02-2021, 03:45 PM
Last Post: Anldra12
  TypeError: a bytes-like object is required, not 'str' ozzy69 1 2,859 Jul-17-2020, 03:38 PM
Last Post: stullis
  Packet Sniffer - TypeError: a bytes-like object is required, not 'str' cheffa2020 4 5,321 Jun-12-2020, 02:10 PM
Last Post: cheffa2020
  Why, TypeError: expected string or bytes-like object ? JohnnyCoffee 3 18,626 May-08-2020, 04:26 AM
Last Post: bowlofred
  TypeError: a bytes-like object is required, not 'str'. jacklee26 4 5,660 Apr-18-2020, 11:04 PM
Last Post: jacklee26
  replace bytes with other byte or bytes BigOldArt 1 10,636 Feb-02-2019, 11:00 PM
Last Post: snippsat
  builtins.TypeError: a bytes-like object is required, not 'str' BigOldArt 0 3,993 Jan-31-2019, 10:46 PM
Last Post: BigOldArt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020