1、登录模块
import requests def test_login(username,password): host='http://localhost' url=f'{host}/api/bbb/ccc' payload={'username':username, 'password':password } reps=requests.post(url,data=payload) return reps.cookies
2、登录后的操作模块,关联cookie增加如下代码即可,方案一:
from Test.login import test_login #导入登录模块里的登录函数 user_cookie= test_login('test','12345678') #调用函数获取返回值并赋值给user_cookie reps=requests.post(api_url,data=payload,cookies=user_cookie)#直接在请求中加上cookies=user_cookie
还可以优化下,因为cookies有时还需要上送其他值,就需要自定义cookies了
1、登录模块,修改下返回值
return reps.cookies['sessionid']
2、登录后的操作模块,增加一步封装
user_session= test_login('test','12345678') #调用函数获取返回值并赋值给user_sessionid user_cookie={'sessionid':user_session}#再封装下赋值给user_cookie,后续操作不变