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相關內容