Requests发送带cookies请求
一、缘 起
最近学习【悠悠课堂】的接口自动化教程,文中提到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(),并update
sess = 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.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上定时构建,即可实现实时监控平台侧消息下发情况并及时反馈报警邮件的需求
OK!
~
~
~
不积跬步,无以至千里
Requests发送带cookies请求的更多相关文章
- 利用postman进行接口测试并发送带cookie请求的方法
做web测试的基本上都用用到postman去做一些接口测试,比如测试接口的访问权限,对于某些接口用户A可以访问,用户B不能访问:比如有时需要读取文件的数据.在postman上要实现这样测试,我们就必要 ...
- python的requests库怎么发送带cookies的请求
背景: 在用robot做接口自动化时,有一个查询接口需要用到登录后返回的token等信息作为cookies作为参数一起请求(token是在返回体中,并不在cookies中), 刚好create se ...
- python使用requests发送multipart/form-data请求数据
def client_post_mutipart_formdata_requests(request_url,requestdict): #功能说明:发送以多部分表单数据格式(它要求post的消息体分 ...
- Python入门:模拟登录(二)或注册之requests处理带token请求
转自http://blog.csdn.net/foryouslgme/article/details/51822209 首先说一下使用Python模拟登录或注册时,对于带token的页面怎么登录注册模 ...
- python使用requests发送application/x-www-form-urlencoded请求数据
def client_post_formurlencodeddata_requests(request_url,requestJSONdata): #功能说明:发送以form表单数据格式(它要求数据名 ...
- requests库的get请求,带有cookies
(一)如何带cookies请求 方法一:headers中带cookies #coding:utf-8 import requests import re # 构建url url = 'http://w ...
- 测试框架httpclent 3.获取cookie的信息,然后带cookies去发送请求
在properties文件里面: startupWithCookies.json [ { "description":"这是一个会返回cookies信息的get请求&qu ...
- requests模块发送带headers的Get请求和带参数的请求
1.在PyCharm开发工具中新建try_params.py文件: 2.try_params.py文件中编写代码: import requests#设置请求Headers头部header = {&qu ...
- Python+requests 发送简单请求--》获取响应状态--》获取请求响应数据
Python+requests 发送简单请求-->获取响应状态-->获取请求响应数据 1.环境:安装了Python和vscode编译器(Python自带的编译器也ok).fiddler抓包 ...
随机推荐
- jmeter接口压测的反思
jmeter接口压测的反思 1.keepalive的坑:连接数满了,导致发起的请求失败. 2.token关联?是数据库取做参数化,还是随机数生成(需要改代码) 3.签名问题如何处理? 4.压测负载机端 ...
- byte的取值范围是-128~127,那么包含-128和127吗?
本帖最后由 王德升老师 于 2019-12-27 17:56 编辑 byte的取值范围为什么是-128~127?如果面试官问你取值范围包含127吗?1. 首先我们知道Java中byte类型是1个字节占 ...
- [USACO5.1] Musical Themes
后缀数组求最长重复且不重叠子串. poj 1743 传送门 洛谷 P2743 传送门 1.子串可以“变调”(即1 3 6和3 5 8视作相同).解决办法:求字符串相邻元素的差形成新串.用新字符串求解最 ...
- PHP常用接口数据过滤的方法
<?php /** * global.func.php 公共函数库 */ /** * 返回经addslashes处理过的字符串或数组 * @param $string 需要处理的字符串或数组 * ...
- R的基础数据结构
- 分布式文件系统与HDFS
HDFS,它是一个虚拟文件系统,用于存储文件,通过目录树来定位文件:其次,它是分布式的,由很多服务器联合起来实现其功能,集群中的服务器有各自的角色. HDFS 的设计适合一次写入,多次读出的场景,且不 ...
- 有用户及目录判断的删除文件内容的Shell脚本
[root@localhost Qingchu]# cat Qingchu_version2.sh #!/bin/bash #描述: # 清除脚本! #作者:孤舟点点 #版本:2.0 #创建时间:-- ...
- 我是青年你是良品-魅蓝NOTE 2
2" title="我是青年你是良品-魅蓝NOTE 2"> 明天魅蓝即将迎来自己的新品发布会.选择儿童节的第二天后最喜爱的手机品牌.让其成为真正青年的良品. 在 ...
- appium ios真机自动化环境搭建&运行(送源码)
appium ios真机自动化环境搭建&运行(送源码) 原创: f i n 测试开发社区 6天前 Appium测试环境的搭建相对比较烦琐,不少初学者在此走过不少弯路 首先是熟悉Mac的使用 ...
- 杀入红海市场 ZUK手机底气在哪?
从越来越奢华的发布会舞台屏幕,到创意越来越烧脑的邀请函,一款新手机的发布工作变得越来越系统化.何时展示.如何亮相,都成为影响一部手机情怀,甚至销售好坏的重要因素.虽然很难以一个固定标准衡量各个手 ...