2.1 middleware.py
# middleware.py
# 这⾥加了⼀个中间件,还要再tting.py中注册⼀下,具体代码⾃⼰百度
import uuid
import json
import threading
import logging
from django import http
from django.utils.deprecation import MiddlewareMixin
soud
from rest_framework import respon as rest_respon
蠢蛋搞怪秀3dlogger = Logger(__name__)
all round
local = threading.local() # 获取当前线程对象
class RequestLogFilter(logging.Filter):
新年祝福语英文"""
⽇志过滤器,将当前请求线程的request信息保存到⽇志的record上下⽂
record带有formater需要的信息。
"""
def filter(lf, record):
try:
record.name = record.name.split('.')[-1]
笑话用英语怎么说except:摩登英语
pass
maleficent
return True
class WechatyApiMiddleware(MiddlewareMixin):
def process_request(lf, request, **kwargs):
youthhostel""" 该⽅法在请求到来的时候调⽤请求参数写⼊⽇志 """
# 以下逻辑是实现请求进来打印相关请求参数
body = request.body.decode()
if body:
try:
body = json.loads(body)
except:
pass
request_info = {
'method': hod,
'path': request.path_info,
'params': request.GET.dict(),
'body': body
}
logger.info(f'requests: {json.dumps(request_info, ensure_ascii=Fal)}')
def process_respon(lf, request, respon):
"""
在执⾏完View函数准备将响应发到客户端前被执⾏ / 响应结果写⼊⽇志
这⾥是打印响应数据的⽇志,多加了⼏个 if 判断
"""
path = request.path_info
if isinstance(respon, rest_respon.Respon) or isinstance(respon, http.JsonRespon): t and path not in filter_path:
logger.info(f'respon: {t.decode("utf-8")}')
elif isinstance(respon, http.HttpResponNotFound):peachy
# 资源不存在
error_data = {
'status': 'error',
'message': f'not found "{path}"'
}
<(json.dumps(error_data, ensure_ascii=Fal))
daybyday