python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错

Posted 小~yytt~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错相关的知识,希望对你有一定的参考价值。

python3编码的请查看这篇文章:https://www.cnblogs.com/575dsj/p/7112767.html

第一次:python3传的是bytes不能是str。好吧,认了。我就传bytes吧

b= hmac.new(\'/admindevice/GetCameraSetting\',\'adbaskjclas\',sha1).hexdigest()
print(b)

--------------------------------------------------------------------------------------------

Traceback (most recent call last):
File "D:/py3_study/run_test/md_code.py", line 23, in <module>
b= hmac.new(\'/admindevice/GetCameraSetting\',\'adbaskjclas\',sha1).hexdigest()
File "F:\\Python36\\lib\\hmac.py", line 144, in new
return HMAC(key, msg, digestmod)
File "F:\\Python36\\lib\\hmac.py", line 42, in __init__
raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got \'str\'

 

来到第二次:看报错,悲催了吧。hmac.new说必须是string才行;

因为hmac.new是要求utf-8的编码

b= hmac.new(bytes(\'/admindevice/GetCameraSetting\'),bytes(\'adbaskjclas\'),sha1).hexdigest()
print(b)

----------------------------------------------------------------

Traceback (most recent call last):
File "D:/py3_study/run_test/md_code.py", line 23, in <module>
b= hmac.new(bytes(\'/admindevice/GetCameraSetting\'),bytes(\'adbaskjclas\'),sha1).hexdigest()
TypeError: string argument without an encoding

 

好吧,hamc.new的要求是UTF-8,我就来转UTF-8,终于成功了

b= hmac.new(bytes(\'/admindevice/GetCameraSetting\',\'utf-8\'),bytes(\'adbaskjclas\',\'utf-8\'),sha1).hexdigest()
print(b)
-------------
结果:792a09ad139522fe77771bc5cb5fbb44b44b40b3

 

这种处理方式也可以,将所有都转成Unicode的方式

a= hmac.new(bytes(\'/admindevice/GetCameraSetting\',\'latin-1\'), bytes(\'adbaskjclas\',\'latin-1\'),sha1).hexdigest()
print(a)
-------------
结果:792a09ad139522fe77771bc5cb5fbb44b44b40b3


base64.b64encode(\'value\')也是相同问题,需要传bytes,然后再转回UTF-8,够恶心吧

原因:
Python 2 悄悄掩盖掉了 byte 到 unicode 的转换,只要数据全部是 ASCII 的话,所有的转换都是正确的,一旦一个非 ASCII 字符偷偷进入你的程序,那么默认的解码将会失效,从而造成 UnicodeDecodeError 的错误。py2编码让程序在处理 ASCII 的时候更加简单。你复出的代价就是在处理非 ASCII 的时候将会失败。

py3也有两种数据类型:str和bytes;  str类型存unicode数据,bytse类型存bytes数据



最长的例子:
quote(base64.b64encode(bytes(hmac.new(bytes(service_key_secret,\'utf-8\'), (bytes(verufy_url,\'utf-8\') +bytes("\\n",\'utf-8\')+ bytes(str(self.timetamp),\'utf-8\')), sha1).hexdigest(),\'utf-8\')))


疑问解答QQ群:群1:588402570  群2:772588688

注:群1有限制的情况下。请进群2

 

关注该公众号:持续更新Jmeter相关内容

以上是关于python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错的主要内容,如果未能解决你的问题,请参考以下文章

Python编码问题

Python2 与 Python3 的编码对比

python2与python3的区别齐全整理

python2与python3的编码问题

python2 与 python3 的编码

python2与python3中编码与解码的区别