前言
为发起请求时能输出日志,所以对requests做二次封装。
config.py文件封装日志,使用loguru模块。
from pathlib import Path
from loguru import logger as log
# 项目根路径
BASE_PATH = Path(__file__).parent.parent
# 日志配置
log.add(BASE_PATH.joinpath("logs/app.log"), encoding="utf-8", level="INFO")
log.add(BASE_PATH.joinpath("logs/警告日志.log"), level="WARNING", encoding="utf-8",
filter=lambda x: "WARNING" in x['level'].name)
log.add(BASE_PATH.joinpath("logs/致命错误日志.log"), level="ERROR", encoding="utf-8",
filter=lambda x: "ERROR" in x['level'].name)
base_requests.py封装requests请求
import functools
import json
import allure
import requests
from config.settings import log, CLIENT_TOKEN, ADMIN_TOKEN, PC_TOKEN
str_req = """
----------------请求参数----------------
请求URL : 【{url}】
请求METHOD : 【{method}】
请求HEADER : 【{header}】
请求BODY : 【{body}】
"""
str_resp = """
----------------响应参数----------------
响应CODE : 【{code}】
响应HEADER : 【{header}】
响应BODY : 【{body}】
"""
class BaseRequest:
# 处理请求字符串格式化,打印日志输出。
@staticmethod
def format_requests(*args, **kwargs):
method, url = args
headers = kwargs.pop("headers", None)
try:
body = json.dumps(kwargs, sort_keys=True, indent=2, ensure_ascii=False)
log.info(str_req.format(url=url, method=method, body=body, header=headers))
except Exception:
log.error("请求数据无法序列化-------")
# 处理响应字符串格式化,打印日志输出。
@staticmethod
def format_response(response):
body = json.dumps(response.json(), sort_keys=True, indent=2, ensure_ascii=False)
log.info(str_resp.format(code=response.status_code, header=response.headers, body=body))
# 处理请求头数据
@staticmethod
def dispose_headers(headers):
default_header = {}
if headers == CLIENT_TOKEN:
default_header['Authorization'] = "Bearer " + CLIENT_TOKEN
elif headers == ADMIN_TOKEN:
default_header['Authorization'] = "Bearer " + ADMIN_TOKEN
elif headers == PC_TOKEN:
default_header['Authorization'] = "Bearer " + PC_TOKEN
else:
return headers
return default_header
def log_request(func):
"""发起请求的函数写成装饰器"""
@functools.wraps(func)
def wrap(*args, **kwargs):
kwargs['headers'] = BaseRequest.dispose_headers(kwargs.get('headers'))
BaseRequest.format_requests(*args, **kwargs)
response = func(*args, **kwargs)
BaseRequest.format_response(response)
return response
return wrap
def allure_attach(func):
"""写入allure报告的装饰器"""
@functools.wraps(func)
def wrap(*args, **kwargs):
method, url = args
headers = BaseRequest.dispose_headers(kwargs.get("headers"))
body_json = kwargs.get("json")
request_json = {"【url】": url, "【method】": method, "【headers】": headers, "【json】": body_json}
allure.attach(json.dumps(request_json, indent=4, ensure_ascii=False), "请求参数")
response_json = func(*args, **kwargs)
allure.attach(json.dumps(response_json.json(), indent=4, ensure_ascii=False), "响应结果")
return response_json
return wrap
@log_request
@allure_attach
def mi_request(method, url, **kwargs):
try:
return requests.request(method, url, **kwargs)
except Exception as e:
log.error(e)
raise e