一、问题
python中一个方法生成的值如何传给另一个方法使用?
二、回答
有3种方式:
1.接收方法A的返回值,传给方法B使用
2.设置全局变量传递值
3.利用pytest的fixture特性传值
第一种方式:接收方法A的返回值,传给方法B使用
1 import requests 2 host = "http://66.66.66.66:9000" 3 def login(): 4 url = host + '/pinter/bank/api/login2' 5 data = {"userName":"admin","password":"1234"} 6 response = requests.post(url=url,data=data) 7 token = response.json().get("data") 8 return token 9 10 def query(token): 11 url = host + '/pinter/bank/api/query2' 12 headers = {"testfan-token": token} 13 data = {"userName": "admin"} 14 response = requests.get(url=url, params=data,headers=headers) 15 print(response.json()) 16 17 token = login() 18 query(token)
第二种方法:设置全局变量传递值
1 import requests 2 3 host = "http://66.66.66.66:9000" 4 token = "" 5 def login(): 6 url = host + '/pinter/bank/api/login2' 7 data = {"userName":"admin","password":"1234"} 8 response = requests.post(url=url,data=data) 9 global token 10 token = response.json().get("data") 11 print(response.json()) 12 print(token) 13 14 def query(): 15 url = host + '/pinter/bank/api/query2' 16 headers = {"testfan-token": token} 17 data = {"userName": "admin"} 18 response = requests.get(url=url, params=data,headers=headers) 19 print(response.json()) 20 21 login() 22 query()
第三种方式:利用pytest的fixture特性传值
getToken方法装上了 @pytest.fixture(),在 testQuery(getToken)中传参,即可获取getToken方法的返回值
1 host = "http://66.66.66.66:9000" 2 3 @pytest.fixture() 4 def getToken(): 5 url = host + '/pinter/bank/api/login2' 6 data = {"userName": "admin", "password": "1234"} 7 response = requests.post(url=url, data=data) 8 assert response.json().get("code") == '0' 9 return response.json().get("data") 10 11 def testQuery(getToken): 12 url = host + '/pinter/bank/api/query2' 13 headers = {"testfan-token": getToken} 14 data = {"userName": "admin"} 15 response = requests.get(url=url, params=data, headers=headers) 16 assert response.json().get("code") == '0'
标签:headers,python,方法,host,url,token,传给,data,response From: https://www.cnblogs.com/miaomiaokaixin/p/17861765.html