最近学习【悠悠课堂】的接口自动化教程,文中提到requests发送带cookies请求的方法,笔者随之也将其用于手头实际项目中,大致如下
实际需求是监控平台侧下发消息有无异常,如有异常便触发报警推送邮件,项目中下发消息接口需要带cookies
脚本的工程名为ynjxhdsendmsg,大致结构如下图
sendmsg.py为主程序,函数checkmsg为在已发消息列表中查找已下发消息,函数sendmsg为发消息并根据结果返回对应的标识 sendalertemail.py为发送邮件程序,在sendmsg.py中根据不同标识调用sendalertemail.py下的send_alert_email函数发报警邮件【重点】发请求之前先加载cookies,方法如下
~......~# 加载cookies# 第一步,引入requestscookiejar()coo = requests.cookies.requestscookiejar()# 第二步,设置cookies参数,coo.set(’key’, ’value’)coo.set(’__utma’, ’82342229.1946326147.***.1545556722.1545556733.4’)coo.set(’jsessionid’, ’d898010550***adb0600bf31ff’)# 第三步,引入seeeion(),并updatesess = requests.session()sess.cookies.update(coo)~......~
sendmsg.py
发送带当前时间戳的特定消息,在发送成功后便于通过时间戳检索 函数checkmsg为在已发消息列表中查找已下发消息 函数sendmsg为发消息并根据结果返回对应的标识 导入sendalertemail模块的send_alert_email方法,在sendmsg.py中根据不同标识调用send_alert_email函数发报警邮件#!/usr/bin/python# coding=utf-8# author: 葛木瓜# 2018.12.20import requestsimport timeimport reimport syssys.path.append(’./’)from sendalertemail import send_alert_emailnow = 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’}# 加载cookiescoo = 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(): """ 在已发送短信列表检查已发送短信 :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_keydef 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(’通知发送已成功’, 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_codeif __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 = "短信已发送,查询已发状态失败!" elif ’check msg connect fail:’ in str(status): alert_content = "短信已发送,无法查询已发状态,报错信息:%s" % status.split(’:’)[-1] elif status == 302: alert_content = "session失效,请重新获取’jsessionid’!" else: alert_content = "短信下发失败,报错信息:%s" % status if alert_content != "normal": send_alert_email(receiver, alert_content)
sendalertemail.py,方法较常见,此处略
完成以上,将脚本放在jenkins上定时构建,即可实现实时监控平台侧消息下发情况并及时反馈报警邮件的需求
以上就是python 实现requests发送带cookies请求的详细内容,更多关于python requests发送带cookies请求的资料请关注软科小院其它相关文章!