This question already has answers here:
Python3 and hmac . How to handle string not being binary
                                
                                    (3个答案)
                                
                        
                                在11个月前关闭。
            
                    
我看到此错误:

TypeError: a bytes-like object is required, not 'str'
    python3.6/base64.py", line 58, in b64encode encoded = binascii.b2a_base64(s, newline=False)`


这是代码:

import base64
import hmac
import hashlib
import binascii

....
def post(self,request):
    body = str(request.body).encode()
    sign_signature = base64.b64encode(hmac.new('tester'.encode(), body, hashlib.sha256).hexdigest())

最佳答案

用以下代码替换您的代码行:

sign_signature = base64.b64encode(hmac.new('tester'.encode(), body, hashlib.sha256).digest())



  digest返回bytes->我们要对其进行b64编码,并且b64encode接受字节,所以我们很好。

关于python - TypeError:需要一个类似字节的对象,而不是'str'-hmac [duplicate],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54051747/

10-09 16:02