python写接口自动化脚本框架实例
时间: 2023-11-30 08:05:00 浏览: 44
以下是一个Python接口自动化测试框架的示例代码:
```
import requests
class APITest:
def __init__(self, base_url):
self.base_url = base_url
def send_request(self, method, path, headers=None, params=None, data=None):
url = self.base_url + path
response = requests.request(method, url, headers=headers, params=params, data=data)
return response
def get(self, path, headers=None, params=None):
return self.send_request('GET', path, headers=headers, params=params)
def post(self, path, headers=None, params=None, data=None):
return self.send_request('POST', path, headers=headers, params=params, data=data)
def put(self, path, headers=None, params=None, data=None):
return self.send_request('PUT', path, headers=headers, params=params, data=data)
def delete(self, path, headers=None, params=None):
return self.send_request('DELETE', path, headers=headers, params=params)
if __name__ == '__main__':
api_test = APITest('https://www.example.com')
response = api_test.get('/api/users', headers={'Authorization': 'Bearer token'})
print(response.status_code)
print(response.json())
```
在这个示例中,我们定义了一个名为`APITest`的类,它有一个`base_url`参数,用于指定API的基本URL。然后我们定义了`send_request`方法,它接受HTTP方法、路径、头、参数和数据,并使用`requests`库发送HTTP请求。然后我们定义了`get`、`post`、`put`和`delete`方法,它们分别使用`send_request`方法发送相应的HTTP请求。
在`if __name__ == '__main__':`块中,我们创建了一个`APITest`对象,并使用`get`方法发送了一个GET请求,并打印了响应的状态代码和JSON响应体。这个示例只是一个简单的示例,可以根据您的需求进行扩展和修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)