主页 > 知识库 > python 实现Requests发送带cookies的请求

python 实现Requests发送带cookies的请求

热门标签:百度AI接口 Win7旗舰版 客户服务 呼叫中心市场需求 语音系统 电话运营中心 企业做大做强 硅谷的囚徒呼叫中心

一、缘 起

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

二、背 景

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

三、说 明

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

  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请求的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
  • python爬虫请求库httpx和parsel解析库的使用测评
  • python爬虫系列网络请求案例详解
  • 详解python requests中的post请求的参数问题
  • 快速一键生成Python爬虫请求头
  • Python3+Django get/post请求实现教程详解
  • python实现三种随机请求头方式
  • Python urllib request模块发送请求实现过程解析
  • python 爬虫请求模块requests详解
  • Python Http请求json解析库用法解析
  • python 发送get请求接口详解
  • python+excel接口自动化获取token并作为请求参数进行传参操作
  • Python使用grequests并发发送请求的示例
  • Python爬虫基础讲解之请求

标签:长沙 喀什 济南 山西 崇左 安康 山西 海南

巨人网络通讯声明:本文标题《python 实现Requests发送带cookies的请求》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266