报错'NoneType' object has no attribute 'upper',修改这个段代码 res = requests.post(url, data = m,headers=header ) res.raise_for_status() res = res.json() return res.get('data',[])
时间: 2024-03-13 15:46:10 浏览: 27
这个错误可能是因为 API 返回的是空值(None),而在空值上调用了字符串方法 upper()。你可以在解析 API 返回值之前增加一个判断,判断返回值是否为 None。如果是,直接返回空列表。
修改后的代码如下:
```
res = requests.post(url, data=m, headers=header)
res.raise_for_status()
res = res.json()
if res is None:
return []
else:
return res.get('data', [])
```
相关问题
报错 'NoneType' object has no attribute 'get' 修改代码 def getData(id): url = "https://wzwlsgmh.wenzhou.gov.cn/api/Public/tableinfo" m = MultipartEncoder(fields={"platform_menu_id": id}) header = {'Content-Type': m.content_type} res = requests.post(url, data=m, headers=header) if res.content: res = res.json() else: return []
这个报错同样是因为返回的数据为空,导致无法执行 `get()` 方法。你可以在调用 `res.json()` 方法之前,先判断一下返回的 JSON 数据是否为空,比如:
```python
def getData(id):
url = "https://wzwlsgmh.wenzhou.gov.cn/api/Public/tableinfo"
m = MultipartEncoder(fields={"platform_menu_id": id})
header = {'Content-Type': m.content_type}
res = requests.post(url, data=m, headers=header)
if res.content:
res = res.json()
if res:
return res.get('data', [])
else:
return []
else:
return []
```
这样可以确保在返回的 JSON 数据为空时,不会执行 `res.get()` 方法,从而避免了出现 `'NoneType' object has no attribute 'get'` 这个错误。
报错'NoneType' object has no attribute 'upper' 修改def getData(id): url = "https://wzwlsgmh.wenzhou.gov.cn/api/Public/tableinfo" m = MultipartEncoder(fields={"platform_menu_id": id}) header = {'Content-Type': m.content_type} res = requests.post(url, data=m, headers=header) res.raise_for_status() res = res.json() if res is None: return [] else: return res.get('data', [])
这个报错通常是因为返回的数据为空,导致无法执行 `upper()` 方法。为了避免这种情况,你可以在调用 `res.json()` 方法之前,先判断一下返回的 `response` 是否为空,比如:
```python
res = requests.post(url, data=m, headers=header)
if res.content:
res = res.json()
# rest of your code
else:
return []
```
这样可以确保在返回的数据为空时,不会执行 `res.json()` 方法,从而避免了出现 `'NoneType' object has no attribute 'upper'` 这个错误。