温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎么实现Requests发送带cookies的请求

发布时间:2021-02-16 15:56:48 来源:亿速云 阅读:548 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关python怎么实现Requests发送带cookies的请求的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一、缘 起

最近学习接口自动化教程,提到Requests发送带cookies请求的方法,随之也将其用于手头实际项目中,大致如下

二、背 景

实际需求是监控平台侧下发消息有无异常,如有异常便触发报警推送邮件,项目中下发消息接口需要带cookies

三、说 明

脚本的工程名为ynJxhdSendMsg,大致结构如下图

python怎么实现Requests发送带cookies的请求

  1. sendMsg.py为主程序,函数checkMsg为在已发消息列表中查找已下发消息,函数sendMsg为发消息并根据结果返回对应的标识

  2. 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(),并update sess = requests.session() sess.cookies.update(coo) ~ ...... ~

sendMsg.py

  1. 发送带当前时间戳的特定消息,在发送成功后便于通过时间戳检索

  2. 函数checkMsg为在已发消息列表中查找已下发消息

  3. 函数sendMsg为发消息并根据结果返回对应的标识

  4. 导入sendAlertEmail模块的send_alert_email方法,在sendMsg.py中根据不同标识调用send_alert_email函数发报警邮件

#!/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():   """   在已发送短信列表检查已发送短信   :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('通知发送已成功', 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 = "短信已发送,查询已发状态失败!"   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的请求”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI