测试开发全栈之Python自动化 requests 之 session 会话管理,只有这一篇我看懂了!!
程序员一凡
·
January 30, 2021
·
1859 hits
「All right reserved, any unauthorized reproduction or transfer is prohibitted」
session 会话管理
1.如何理解 http 协议里的无状态
2.为什么用到 cookie
3.为什么要用到会话管理?
4.手动传入 cookie
5.session 会话管理
1.如何理解 http 协议里的无状态
比如商场购物车,你把东西放到购物车,如果 http 协议的话,刷新页面,购物车就为空了
简单理解就是 http 刷新后就不会记得你之前做了什么
2.为什么用到 cookie
web2.0 交互时代,所以就引用 cookie 和 seesion 来记录状态,比如登录
3.为什么要用到会话管理?
如果很多个接口都要用到 cookies,如果每次都要手动传 cookies 是不是很麻烦???
4.手动传入 cookie
请求购物车接口 (没有登录的情况),如果没传入 cookie,就无法查看到购物车里的商品(就是刚刚说的 httpt 是无状态的)
请求购物车接口时,必须手动带上 cookie 参数,才能查看到购物车内的商品
那么有没有一种方式,订单接口自动能带上 cookeis?不用手动去传 cookies!
# -*- coding: utf-8 -*-
# @Author : 微信公众号程序员一凡
import requests
# 登录接口
log_url = "http://shopxo.hctestedu.com/index.php?s=/index/user/login.html"
# 登录参灵敏
data = {"accounts": "laozhu",
"pwd": "123456"}
# 头部信息
head = {"X-Requested-With": "XMLHttpRequest"}
login_response = requests.post(log_url, data=data, headers=head)
# 获取cookie,传给下面订单接口
cookie = login_response.cookies
# 订单接口
order_url = "http://shopxo.hctestedu.com/index.php?s=/index/cart/index.html"
order_response = requests.get(order_url, cookies=cookie)
print(order_response.text)
5.session 会话管理
可以保持会话,将 cookies 等值自动传到下一个接口 (注意:是自动传到下一个接口)
换句话说,就是不用手动去传 cookie 的值
# -*- coding: utf-8 -*-
# @Author : 微信公众号程序员一凡
import requests
# 登录接口
log_url = "http://shopxo.hctestedu.com/index.php?s=/index/user/login.html"
# 登录参灵敏
data = {"accounts": "laozhu",
"pwd": "123456"}
# 头部信息
head = {"X-Requested-With": "XMLHttpRequest"}
# 实例化session对像
session = requests.session()
login_response = session.post(log_url, data=data, headers=head)
# 订单接口
order_url = "http://shopxo.hctestedu.com/index.php?s=/index/cart/index.html"
# 不用手动传入cookies值,因为session自动带上了
order_response = session.get(order_url)
print(order_response.text)
# 打印cookies
print(session.cookies)
最后:
未来的你肯定会感谢现在努力的自己!
TesterHome 为用户提供「保留所有权利,禁止转载」的选项。
除非获得原作者的单独授权,任何第三方不得转载标注了「All right reserved, any unauthorized reproduction or transfer is prohibitted」的内容,否则均视为侵权。
具体请参见TesterHome 知识产权保护协议。
No Reply at the moment.