本文來自檸檬班py30期學員,處理公司接口請求時遇到的問題及相應的解決方案。html
以本文做爲記錄,方便其它學員遇到相似問題時,能夠參考解決。python
嘗試用python語言的requests庫,編寫腳本登錄公司的APP。算法
問題1:json
將手機號、密碼數據傳入後,始終登錄不成功,通過與開發溝通後知道須要簽名才能登錄。工具
問題2:post
簽名算法寫好後仍然沒法登錄成功。網站
經過後臺日志發現是傳入數據格式不正確致使的,公司的post接口入參方式爲form-data , 而我是用json串的方式入參的。ui
一、簽名時須要的時間戳編碼
import time t = time.time() print (t) #原始時間數據 print (int(t)) #秒級時間戳 print (int(round(t * 1000))) #毫秒級時間戳 print (int(round(t * 1000000))) #微秒級時間戳 # 取出來的時間戳想驗證時間是否正確,能夠百度(https://tool.lu/timestamp/)在線時間戳工具轉換看看
二、簽名時須要的MD5加密加密
import hashlib data = 「待加密數據」 m = hashlib.md5(data)
Tips:
如遇報錯:Unicode-objects must be encoded before hashing
解決方法:
此處必須爲encode,可是python3此處默認爲unicode,因此修改以下:
hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()
注:編碼方式有不少種,此處用UTF-8編碼舉例,實際中可按照編碼不一樣本身選擇
三、發送http請求時,以form-data的格式做爲requests的參數
使用requests的requests_toolbelt模塊 ,須要自行安裝。
from requests_toolbelt import MultipartEncoder import requests m = MultipartEncoder( fields={'field0': 'value', 'field1': 'value', 'field2': ('文件名稱', open('文件地址/file.py', 'rb'), 'text/plain')} ) r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
requests官方網站地址:https://www.osgeo.cn/requests/user/quickstart.html#more-complicated-post-requests
requests_toolbelt官方網站地址:https://toolbelt.readthedocs.io/en/latest/user.html