python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错,python3python2,python3编码的
python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错,python3python2,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数据
python3与python2编码导致 hmac.new/base64.b64encode('value') python3各种报错
相关内容
- python redis客户端使用lua脚本,redislua,有一个需求,为一
- python爬取视频网站m3u8视频,下载.ts后缀文件,合并成整
- 写一个函数,识别字符串是否符合python语法的变量名,
- 一个案例深入Python中的__new__和__init__,__new___init_,准备
- python 读取文件第一列 空格隔开的数据,,file=open(
- python算两个时间之间的天数,将天数转成int型,python
- python——求交通肇事者的车牌号,python交通肇事,例子:
- Python包和版本管理的最好工具----pipenv,python----pipenv,
- python学习之遇到得基础报错,python学习基础报,error01:
- python实现本地图片上传到服务区,,本地图片上传到服务
评论关闭