cookies处理

requests.utils.dict_from_cookiejar函数:Jacookiejar和字典格式之间的转换

1.创建获取cookie的函数

def create_cookies():
endpoint = '/common/fgadmin/login'
url = base.get_url(endpoint)
method='post'
headers = {'content-type': 'application/json'}
json={’。。。'}
DataAll={'json':json,'headers':headers}
result=base.get_response(url,method,**DataAll) //一个封装过的requests函数
print(result.text)
print(result.cookies)
    cookies=requests.utils.dict_from_cookiejar(result.cookies) //格式转换Jacookiejar和字典格式之间的转换
print(cookies)


》》》

{"message":"success","code":200}

result.cookies的输出
<RequestsCookieJar[<Cookie smartcamera_buy_pc_fg_sessionid=smartcamera_buy_pc_fg_sessionid_74966314_3f4c477d-36d3-4d7c-860b-dc68d34b3ec9 for .study-perf.qa.netease.com/>, <Cookie smartcamera_buy_pc_fg_short_sessonid=smartcamera_buy_pc_fg_short_sessonid_74966314_fa606ddc-ca0d-4a4b-b5d4-62593036665a for .study-perf.qa.netease.com/>]>

经requests.utils.dict_from_cookiejar 转换后的格式:

{'smartcamera_buy_pc_fg_sessionid': 'smartcamera_buy_pc_fg_sessionid_74966314_3f4c477d-36d3-4d7c-860b-dc68d34b3ec9', 'smartcamera_buy_pc_fg_short_sessonid': 'smartcamera_buy_pc_fg_short_sessonid_74966314_fa606ddc-ca0d-4a4b-b5d4-62593036665a'}

 

2.使用cookies, 经过转换后的cookie,为字典,可以直接传参给 requests.post(url,cookies=cookies,headers=headers)

def test_addaddress_success_addressnew_1(self):
'''添加收货地址成功'''

cookies={'smartcamera_buy_pc_fg_sessionid':'smartcamera_buy_pc_fg_short_sessonid_74966314_13b6c96f-787f-45d0-8432-77adb5947ce2',
'smartcamera_buy_pc_fg_short_sessonid':'smartcamera_buy_pc_fg_sessionid_74966314_087b217e-2513-4ff5-8f2a-74794fe155af'}
cookies2=base.get_cookies()//cookies与cookies2效果相同
    
print(cookies2)
headers= {'content-type': 'application/json'}
json = {'...'}


DataAll={'cookies':cookies2,'headers':headers,'json':json}
result=base.get_response(url,method,**DataAll)
posted @ 2017-08-21 11:33  必有回响  阅读(250)  评论(0编辑  收藏  举报