大家都对cookie都不陌生,我们本篇文章使用requests结合cookie进行实例演示。我们使用一个接口项目地址,因为接口项目涉及到隐私问题,所以这里接口的地址我暂时不会给大家开放,但是我会给大家演示一个整体cookie的处理流程,因为这部分在实际的接口测试中是十分重点的。大家只需要把处理cookie的流程和原理整明白了,其他的就都好说了。。。我们接下开始干:
首先呢,我们要知道整个cookie的一个实现:
其实cookie是一个客户端的机制,关于cookie的实现其实是很复杂的。大家可以访问这篇文章去学习和了解:深入理解cookie和session ok,我们了解了什么是cookie以后在来看下面的操作。首先我们要知道cookie的一个整个请求处理流程:
1.发送登陆请求
2.登陆成功后
3.获取session信息并返回
4.带着登陆成功后的session登陆后的其他接口
在访问登陆接口时,我们先开启charles进行抓包,然后在定义一个login方法,来看代码的实现方法:
抓取登陆请求后,我们使用requests进行编写login接口:
import requests
def login():
r = requests.post(
'http://xxxxxxx:20080/auth/login',
data={"username":'system',"password":"123456"}
)
return r.json()
print (login())
我们查看登陆后,系统返回的结果:
C:Python35python.exe E:/project/index.py
{'code': 200}
Process finished with exit code 0
很明显,返回了一个code=200的状态码,这个并不是我们需要的,我们需要的是登陆后,服务器返回的session,我们要获取这个Session,方便我们访问系统的其他接口,所以,这里面,我们需要使用一个特殊的方法来获取登陆系统后,服务器返回的session,继续往下看,我们将上面的代码进行处理: r.cookies是获取服务器返回的session方法
import requests
def login():
r = requests.post(
'http://xxxxxxx:20080/auth/login',
data={"username":'system',"password":"123456"}
)
return r.cookies
print (login())
返回结果:
<RequestsCookieJar[<Cookie port=20080 for 117.39.63.66/>, <Cookie session=.eJwdjsuKwkAQRX9Fau0ibesmMIuGSJNAdxGoGKo2wmh8lMkmjsRp8d8nzvZwz-W8YH8au_sF8p_x0S1hfz1C_oLFN-SAPqyDbldIO-U2bIQOv-hrw63ceKgT68EK8SYOpYnaGKHGiopyclZ8MyGFp2h_ZS2nD0dqMmznDUkvhQyh_Xhyi-qykESDryde7fqQI7gveS3jcu_G_Hwy8_wA-akbj.DlapFg.6CIk-zQ13C3TbJ-mjjNP_tpxySw for 117.39.63.66/>]>
OK,我们得到了服务端返回的cookies,类似这种的<Cookie session=.eJwdjsuKwkAQRX9Fau0ibesmMIuGSJNAdxGoGKo2wmh8lMkmjsRp8d8nzvZwz-W8YH 然后我们取到session,使用的方法是:r.cookies["session"],看代码如下:
import requests
def login():
r = requests.post(
'http://xxxxxxx:20080/auth/login',
data={"username":'system',"password":"123456"}
)
return r.cookies['session']
print (login())
返回结果如下:
.eJwdjsuKwkAQRX9Fau0ibesmMIuGSJNAdxGoGKo2wmh8lMkmjsRp8d8nzvZwz-W8YH8au_sF8p_x0S1hfz1C_oLFN-SAPqyDbldIO-U2bIQOv-hrw63ceKgT68EK8SYOpYnaGKHGiopyclZ8MyGFp2h_ZS2nD0dqMmznDUkvhQyh_Xhyi-qykESDryde7fqQ2GBx7KOyRV8N828KdE5M1QWpnptKK4XLkCplcs9I7gveS3jcu_G_Hwy8_wA-akbj.Dlaprw.y-qE1LxdvCMnz0W9B87H6Cv8W80
ok,整个cookie的获取流程我们就到这里了。假设如果我们不带上session,直接访问系统的其它任意一个接口,我们来看一下是否可以呢?我们继续定义一个方法,叫getInfo,代码如下:
import requests
def login():
r = requests.post(
'http://xxxxxxx:20080/auth/login',
data={"username":'system',"password":"123456"}
)
return r.cookies['session']
def getInfo():
r =requests.get('http://xxxxx:20080/settings/option/cloud/data')
return r.text
print(getInfo())
查看返回结果:
C:Python35python.exe E:/project/index.py
<!DOCTYPE html>
<!--[if IE 8]>
<html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]>
<html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>
xxxxxxxxx系统
</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="../static/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../static/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../static/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css" />
<!-- BEGIN PAGE LEVEL STYLES -->
<link href="../static/pages/css/login-1.min.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="/static/img/favicon.ico" /> </head>
<!-- END HEAD -->
<body class=" login">
<div id="wrapper">
<div class="login_box">
<form class="login-form" action="/auth/login" method="post" onsubmit="return false;">
<div class="alert alert-danger display-hide" style="display: none">
<button class="close" data-close="alert"></button>
<span> 请输入用户名密码. </span>
</div>
<div class="login_right">
<div class="login_wrapper">
<div class="park_icon">
<div class="left">
<img src="/static/img/login_icon.png" alt="">
</div>
<div class="right">
<img src="/static/img/login_text.png" alt="">
</div>
</div>
<div class="title">
xxxxxxxxxx
系统 </div> <div class="input_box"> <div class="form-group"> <div class="input-icon"> <input class="form_login" type="text" placeholder="用户名" name="username" /> </div> </div> <div class="form-group"> <div class="input-icon"> <input class="form_login" type="password" placeholder="密码" name="password" /> </div> </div> </div> <button type="submit" class="btn white pull-right"> 登录 </button> </div> </div> </form> </div> </div> <script src="../static/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../static/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../static/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <!-- BEGIN PAGE LEVEL PLUGINS --> <script src="../static/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script> <script src="../static/global/plugins/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script> <!-- END PAGE LEVEL PLUGINS --> <!-- BEGIN THEME GLOBAL SCRIPTS --> <script src="../static/global/scripts/app.min.js" type="text/javascript"></script> <!-- END THEME GLOBAL SCRIPTS --> <!-- BEGIN PAGE LEVEL SCRIPTS --> <script type="text/javascript"> jQuery(document).ready(function() { $(".login-form").validate({ errorElement: "span", errorClass: "help-block", focusInvalid: !1, rules: { username: { required: !0 }, password: { required: !0 }, remember: { required: !1 } }, messages: { username: { required: "用户名不能为空." }, password: { required: "密码不能为空." } }, invalidHandler: function(e, r) { $(".alert-danger span").text("请输入用户名密码."); $(".alert-danger", $(".login-form")).show() }, highlight: function(e) { $(e).closest(".form-group").addClass("has-error") }, success: function(e) { e.closest(".form-group").removeClass("has-error"), e.remove() }, errorPlacement: function(e, r) { e.insertAfter(r.closest(".input-icon")) }, submitHandler: function(e) { $('button').html('正在登录...').css('opacity', '0.5').css('cursor', 'progress'); $('#username, #password').attr('disabled', 'disabled'); var postData = $(e).serialize(); $.post("/auth/login", postData, function(data) { if (data.code == 200) { window.location.href = "/"; } else { $(".alert-danger span").text(data.err_msg); $(".alert-danger", $(".login-form")).show(); $('button').html('登录').css('opacity', '1').css('cursor', 'pointer'); $('#username, #password').removeAttr('diabled'); } }); return false; } }); $(".login-form input").keypress(function(e) { return 13 == e.which ? ($(".login-form").validate().form() && $(".login-form").submit(), !1) : void 0 }); }); </script> </body> </html> Process finished with exit code 0
答案显而易见,我们没有登录成功,所以这个接口我们是无法访问的.这时候我们就要带上session来访问我们刚刚的接口了,我们继续来看 加上session后的整个代码的处理:
import requests
def login():
r = requests.post(
'http://117.39.xxxx/auth/login',
data={"username":'system',"password":"123456"}
)
return r.cookies['session']
def getInfo():
r =requests.get('http://117.39.xxxxx/settings/option/cloud/data',
cookies={"session":login()}) #增加session
return r.json()
print(getInfo())
查看返回的结果:
{'code': 200, 'data': {'cloud_ip': {'value': 'sc.parkingwang.com'}, 'waiting_enable_flag': {'value': '0'}, 'parkno_type': {'value': 0}, 'terminal_operator': {'value': '192.168.199.1'}, 'total_full_limit_type': {'value': '1'}, 'tmp_full_limit_flag': {'value': '0'}, 'cloud_port': {'value': '9001'}, 'arm_no': {'value': '7100000005'}, 'connected': {'value': '1'}, 'pic_upload': {'value': '1'}, 'cloud_url': {'value': 'http://api.com/picupload/'}, 'auth_car_waiting_enable_flag': {'value': '0'}, 'fixed_full_limit_flag': {'value': '0'}}}
很明显,我们登录成功了,系统的接口也访问成功了。