import pytest,requests,jsonpath params = { "application": "app", "application_client_type": "weixin", } header ={ "application": "app", "application_client_type": "weixin", "token":"token_list" } data = { "accounts":"huace_xm", "pwd":"123456", "type":"username" } def test_01(): res = requests.post \ (url="http://shop-xo.hctestedu.com/index.php?s=api/user/login", params=params, data=data) print(res.text) # print(res.json()["data"]["token"]) token_list = jsonpath.jsonpath(res.json(), "$..token") print(token_list) # 转成json数据 --字典的写法 def test_02(): data2 = { "id": "12" } res1 = requests.post \ (url="http://shop-xo.hctestedu.com/index.php" "?s=api/goods/favor&token=" + token_list[0], params=params, data=data2) print(res1.text)这个代码报错原因为什么是E NameError: name 'token_list' is not defined
时间: 2023-11-27 18:04:52 浏览: 33
这个代码报错是因为`token_list`变量只在`test_01`函数中被定义,而在`test_02`函数中却没有被定义。因此,当`test_02`函数中的代码尝试使用`token_list`变量时,Python会抛出一个`NameError`异常,提示该变量未被定义。
要解决这个问题,可以将`token_list`变量定义为全局变量,使它在整个程序中都可以被访问。具体来说,可以将其定义在函数外部,例如:
```
import pytest
import requests
import jsonpath
params = {
"application": "app",
"application_client_type": "weixin",
}
header = {
"application": "app",
"application_client_type": "weixin",
"token": "token_list",
}
data = {
"accounts": "huace_xm",
"pwd": "123456",
"type": "username",
}
# 定义全局变量
token_list = []
def test_01():
global token_list # 声明使用全局变量
res = requests.post(
url="http://shop-xo.hctestedu.com/index.php?s=api/user/login",
params=params,
data=data
)
print(res.text)
token_list = jsonpath.jsonpath(res.json(), "$..token")
print(token_list)
def test_02():
global token_list # 声明使用全局变量
data2 = {
"id": "12"
}
res1 = requests.post(
url="http://shop-xo.hctestedu.com/index.php?s=api/goods/favor&token=" + token_list[0],
params=params,
data=data2
)
print(res1.text)
```
在这个例子中,我们将`token_list`变量定义为全局变量,并在`test_01`和`test_02`函数中都声明使用全局变量。这样,在`test_01`函数中赋值给`token_list`变量的值就可以在`test_02`函数中使用了。