python 實現(xiàn)Requests發(fā)送帶cookies的請求
一、緣 起
最近學習【悠悠課堂】的接口自動化教程,文中提到Requests發(fā)送帶cookies請求的方法,筆者隨之也將其用于手頭實際項目中,大致如下
二、背 景
實際需求是監(jiān)控平臺側(cè)下發(fā)消息有無異常,如有異常便觸發(fā)報警推送郵件,項目中下發(fā)消息接口需要帶cookies
三、說 明
腳本的工程名為ynJxhdSendMsg,大致結(jié)構(gòu)如下圖
- sendMsg.py為主程序,函數(shù)checkMsg為在已發(fā)消息列表中查找已下發(fā)消息,函數(shù)sendMsg為發(fā)消息并根據(jù)結(jié)果返回對應的標識
- sendAlertEmail.py為發(fā)送郵件程序,在sendMsg.py中根據(jù)不同標識調(diào)用sendAlertEmail.py下的send_alert_email函數(shù)發(fā)報警郵件
四、實 現(xiàn)
【重點】發(fā)請求之前先加載cookies,方法如下
~ ...... ~ # 加載cookies # 第一步,引入RequestsCookieJar() coo = requests.cookies.RequestsCookieJar() # 第二步,設置cookies參數(shù),coo.set('key', 'value') coo.set('__utma', '82342229.1946326147.***.1545556722.1545556733.4') coo.set('JSESSIONID', 'D898010550***ADB0600BF31FF') # 第三步,引入seeeion(),并update sess = requests.session() sess.cookies.update(coo) ~ ...... ~
sendMsg.py
- 發(fā)送帶當前時間戳的特定消息,在發(fā)送成功后便于通過時間戳檢索
- 函數(shù)checkMsg為在已發(fā)消息列表中查找已下發(fā)消息
- 函數(shù)sendMsg為發(fā)消息并根據(jù)結(jié)果返回對應的標識
- 導入sendAlertEmail模塊的send_alert_email方法,在sendMsg.py中根據(jù)不同標識調(diào)用send_alert_email函數(shù)發(fā)報警郵件
#!/usr/bin/python # coding=utf-8 # author: 葛木瓜 # 2018.12.20 import requests import time import re import sys sys.path.append('./') from sendAlertEmail import send_alert_email now = time.strftime('%Y.%m.%d %H:%M:%S') # 獲取當前時間 sendMsg_url = 'http://*.*.*.*/interactive/sendMessage.action' msgList_url = 'http://*.*.*.*/interactive/sendedMessageList.action' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0', 'Content-Type': 'application/x-www-form-urlencoded' } payload = { 'showFlag': '0', 'type': '1', 'fsnl': 'on', 'receiversId_': '63110542', 'receiveName': '9705家長;', 'content': 'Test msg sending,time ' + now, 'templateType': '1', 'addTeachername': '0', 'isGreed': '0', 'send': '1', 'startDayTime': '2018-12-20', 'hourss': '22', 'munit': '29', 'selectRole': '2', 'receiversIds': '63110542', 'templateFlag': '0' } # 加載cookies coo = requests.cookies.RequestsCookieJar() coo.set('__utma', '82342229.1946326147.***.1545556722.1545556733.4') coo.set('JSESSIONID', 'D898010550***ADB0600BF31FF') sess = requests.session() sess.cookies.update(coo) def checkMsg(): """ 在已發(fā)送短信列表檢查已發(fā)送短信 :return: """ i = 1 while True: try: cm_resp = sess.get(msgList_url, headers=headers, allow_redirects=False) except Exception as e: return str(e) else: time.sleep(1) cm_key = re.findall('Test msg sending,time33 ' + now, cm_resp.text) i += 1 if i <= 30: if len(cm_key): break else: cm_key = ['More than 30 times,no result'] break print('Request %d times' % i) return cm_key def sendMsg(): """ send message :return: """ try: resp = sess.post(sendMsg_url, headers=headers, data=payload, allow_redirects=False) except Exception as e: return str(e) else: if resp.status_code == 200: key = re.findall('通知發(fā)送已成功', resp.text) cm_key = checkMsg() # print(key, cm_key) if len(key) and len(cm_key): if cm_key[0] == 'Test msg sending,time ' + now: return 200 elif cm_key[0] == 'More than 30 times,no result': return 'More than 30 times,no result' else: # print('Check Msg connect fail:' + str(cm_key)) return 'Check Msg connect fail: ' + cm_key elif resp.status_code == 302: return 302 else: return resp.status_code if __name__ == '__main__': receiver = ['**@***.com'] # 收件人郵件列表 status = sendMsg() print(status) if status == 200: alert_content = "normal" print('Test Success!') elif status == 'More than 30 times,no result': alert_content = "短信已發(fā)送,查詢已發(fā)狀態(tài)失?。? elif 'Check Msg connect fail:' in str(status): alert_content = "短信已發(fā)送,無法查詢已發(fā)狀態(tài),報錯信息:%s" % status.split(':')[-1] elif status == 302: alert_content = "Session失效,請重新獲取'JSESSIONID'!" else: alert_content = "短信下發(fā)失敗,報錯信息:%s" % status if alert_content != "normal": send_alert_email(receiver, alert_content)
sendAlertEmail.py,方法較常見,此處略
五、最 后
完成以上,將腳本放在jenkins上定時構(gòu)建,即可實現(xiàn)實時監(jiān)控平臺側(cè)消息下發(fā)情況并及時反饋報警郵件的需求
以上就是python 實現(xiàn)Requests發(fā)送帶cookies請求的詳細內(nèi)容,更多關(guān)于python Requests發(fā)送帶cookies請求的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python實現(xiàn)定時自動清除瀏覽器cookies的方法
- Python獲取瀏覽器Cookies的方法總結(jié)
- 詳解Python?Flask?API?示例演示(附cookies和session)
- Python?selenium?get_cookies獲取cookie不全的解決方案
- python+selenium自動化實戰(zhàn)攜帶cookies模擬登陸微博
- cookies應對python反爬蟲知識點詳解
- Python爬蟲使用瀏覽器cookies:browsercookie過程解析
- python編程之requests在網(wǎng)絡請求中添加cookies參數(shù)方法詳解
- Python獲取瀏覽器Cookies的四種方式小結(jié)
相關(guān)文章
使用Python一鍵提取PDF中的表格到Excel的方法詳解
從PDF文件獲取表格中的數(shù)據(jù),也是日常辦公容易涉及到的一項工作,一個一個復制吧,效率確實太低了,用Python從PDF文檔中提取表格數(shù)據(jù),并寫入Excel文件,灰?;页8咝?本文就給大家介紹一下如何使用Python一鍵提取PDF中的表格到Excel,需要的朋友可以參考下2023-08-08Python運維之獲取系統(tǒng)CPU信息的實現(xiàn)方法
今天小編就為大家分享一篇Python運維之獲取系統(tǒng)CPU信息的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06Python?+?Tkinter連接本地MySQL數(shù)據(jù)庫簡單實現(xiàn)注冊登錄
這篇文章主要介紹了Python?+?Tkinter連接本地MySQL數(shù)據(jù)庫簡單實現(xiàn)注冊登錄。下面文章著情介紹,需要的小伙伴可以參考一下2022-01-01Python3爬蟲里關(guān)于Splash負載均衡配置詳解
在本篇文章里小編給大家分享了關(guān)于Python3爬蟲里關(guān)于Splash負載均衡配置的相關(guān)內(nèi)容,需要的朋友們可以學習參考下。2020-07-07Python利用AutoGrad實現(xiàn)自動計算函數(shù)斜率和梯度
AutoGrad 是一個老少皆宜的 Python 梯度計算模塊。對于大學生、機器學習愛好者而言,你只需要傳遞給它Numpy這樣的標準數(shù)據(jù)庫下編寫的損失函數(shù),它就可以自動計算損失函數(shù)的導數(shù)(梯度)。本文將從普通斜率計算開始,介紹到如何只使用它來實現(xiàn)一個邏輯回歸模型2022-07-07