基于requests的二次封装

## 基础方法的封装

### 基础环境的管理

> 使用yml文件做环境、配置管理

<!--env.yml-->

```yaml
QA: http://qa.baidu.com
UAT: http://uat.baidu.com
Prod: Http://www.baidu.com
```

<!--load_yaml.py-->

```python
import yaml
import os


def get_host(env='QA'):
filename = os.path.join(os.path.dirname(__file__), 'env.yml').replace(
"\\", "/")
with open(filename, 'r', encoding='utf-8') as f:
hosts = yaml.load(f.read())
return hosts.get(env, None)
```

<!--test_load_yaml.py-->

```python
import pytest
from load_yaml import get_host


def test_host_in_yaml():
result = get_host('QA')
assert result == 'http://qa.baidu.com'


def test_host_not_in_yaml():
result = get_host('Dev')
assert result is None
```

### 日志模块

> 通过装饰器实现日志模块

<!--api_log.py-->

```python
import logging

logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO)


def logger(func):
'''
Add some log information before function run and after function run
'''

def wrapper(*arg, **kw):
logging.info("Begin to execute function: {} and parameter was {},{}".
format(func.__name__, arg, kw))
func(*arg, **kw)
logging.info("Finish executing function: {}".format(func.__name__))

return wrapper
```

### 基础功能封装

<!--Session.py-->

```python
from requests import Session

def get_session():
with Session as s:
return s
```

<!--api_helpper.py-->

```python
from requests import Session
import logging

logging.basicConfig(format='[%(asctime)s] %(message)s', level=logging.INFO)


def get_session():
with Session() as s:
return s


class BaseApi(object):
def __init__(self, session):
self.session = session
self.timeout = 30
self.verify = False

def _get(self, url, params, header={}):
try:
logging.info("Start to request '{}'".format(url))
response = self.session.get(
url=url,
params=params,
timeout=self.timeout,
verify=self.verify,
headers=header)
logging.info("The request parameter was '{}'".format(params))
logging.info("The response status code was '{}'".format(
response.status_code))
except Exception as e:
response = '{}'.format(e)
logging.error(
"The request was failed, error message was '{}'".format(e))
finally:
return response
```

## 业务方法的封装

<!--BaiDu.py-->

```python
class BaiDu(BaseApi):
def get_baidu_index(self, host=r'http://www.baidu.net', uri=r'/'):
response = self._get('{}{}'.format(host, uri), params=None)
return response.text, response.status_code
```

猜你喜欢

转载自www.cnblogs.com/ZH-X/p/11403472.html