python 实现Requests发送带cookies的请求

(编辑:jimmy 日期: 2024/11/11 浏览:2)

一、缘 起

最近学习【悠悠课堂】的接口自动化教程,文中提到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请求的详细内容,更多关于python Requests发送带cookies请求的资料请关注其它相关文章!