码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-11 11:34:09      阅读:5379      评论:0      收藏:0      [点我收藏+]

标签:out   print   dede   文章   py3   两种   min   ack   nic   

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数据

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

标签:out   print   dede   文章   py3   两种   min   ack   nic   

原文地址:https://www.cnblogs.com/xiaoxiao-niao/p/8266768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!