封装一个简单的axios帮助类
时间: 2023-11-29 10:46:18 浏览: 75
ts封装简单封装axios
以下是一个简单的axios帮助类的封装方法,可以用于发送GET和POST请求,并对请求的各种异常情况进行处理:
```python
import axios
class AxiosHelper:
def __init__(self, base_url):
self.base_url = base_url
def get(self, url, params=None):
try:
response = axios.get(self.base_url + url, params=params)
return response.json()
except Exception as e:
print("Error occurred while sending GET request: ", e)
return None
def post(self, url, data=None):
try:
response = axios.post(self.base_url + url, data=data)
return response.json()
except Exception as e:
print("Error occurred while sending POST request: ", e)
return None
```
使用示例:
```python
helper = AxiosHelper("https://api.example.com")
response = helper.get("/users", {"page": 1})
if response:
print(response)
else:
print("Failed to get response")
response = helper.post("/login", {"username": "user", "password": "pass"})
if response:
print(response)
else:
print("Failed to get response")
```
阅读全文