python 实现Requests发送带cookies的请求

时间:2022-09-18 18:07:22

一、缘 起

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

二、背 景

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

三、说 明

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

python 实现Requests发送带cookies的请求

  1. sendmsg.py为主程序,函数checkmsg为在已发消息列表中查找已下发消息,函数sendmsg为发消息并根据结果返回对应的标识
  2. sendalertemail.py为发送邮件程序,在sendmsg.py中根据不同标识调用sendalertemail.py下的send_alert_email函数发报警邮件

四、实 现

【重点】发请求之前先加载cookies,方法如下

python" id="highlighter_215588">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
~
......
~
# 加载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函数发报警邮件
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/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请求的详细内容,更多关于python requests发送带cookies请求的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/freedomlidi/p/12431307.html