原文作者:我辈李想
版权声明:文章原创,转载时请务必加上原文超链接、作者信息和本声明。
文章目录
- 前言
- 一、常见用法
- 二、JWT中间价
- 三、操作日志中间件
- 1.在user的app下建立models类
- 2.如图位置新建LogMiddleware.py
- 3.django中添加中间件
- 四、全局异常中间件
- 1.新建Exception.py文件
- 2.django配置添加异常中间件
前言
通俗来说,中间件存在于系统开发中,目前有2种,一种是作用于前端和后端之间,一种是作用于后端系统中的,这里说的中间件是django后端。django的前后端分离项目和前后端不分离项目都使用到中间件。
一、常见用法
二、JWT中间价
三、操作日志中间件
这个是参考网络上的文章,进行少量修改。
1.在user的app下建立models类
class OpLogs(models.Model):
"""操作日志"""
id = models.AutoField(primary_key=True)
re_time = models.CharField(max_length=32, verbose_name='请求时间')
re_user = models.CharField(max_length=32, verbose_name='操作人')
re_ip = models.CharField(max_length=32, verbose_name='请求IP')
re_url = models.CharField(max_length=255, verbose_name='请求url')
re_method = models.CharField(max_length=11, verbose_name='请求方法')
re_content = models.TextField(null=True, verbose_name='请求参数')
rp_content = models.TextField(null=True, verbose_name='响应参数')
access_time = models.IntegerField(verbose_name='响应耗时/ms')
class Meta:
verbose_name = '操作日志'
verbose_name_plural = '操作日志'
db_table = 'operate_logs'
2.如图位置新建LogMiddleware.py
# -*- coding:utf-8 _*-
"""
@author:lenovo
@file: LogMiddleware.py
@time: 2023/3/17 17:41
"""
import time
import json
from django.utils.deprecation import MiddlewareMixin
from user.models import OpLogs
class OpLog(MiddlewareMixin):
__exclude_urls = ['index/', ] # 定义不需要记录日志的url名单
def __init__(self, *args):
super(OpLog, self).__init__(*args)
self.start_time = None # 开始时间
self.end_time = None # 响应时间
self.data = {} # dict数据
def process_request(self, request):
"""
请求进入
:param request: 请求对象
:return:
"""
self.start_time = time.time() # 开始时间
re_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) # 请求时间(北京)
# 请求IP
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
# 如果有代理,获取真实IP
re_ip = x_forwarded_for.split(",")[0]
else:
re_ip = request.META.get('REMOTE_ADDR')
# 请求方法
re_method = request.method
# 请求参数
re_content = request.GET if re_method == 'GET' else request.POST
if re_content:
re_content = json.dumps(re_content)
else:
re_content = None
self.data.update(
{
're_time': re_time, # 请求时间
're_url': request.path, # 请求url
're_method': re_method, # 请求方法
're_ip': re_ip, # 请求IP
're_content': re_content, # 请求参数
}
)
def process_response(self, request, response):
"""
响应返回
:param request: 请求对象
:param response: 响应对象
:return: response
"""
# 请求url在 exclude_urls中,直接return,不保存操作日志记录
for url in self.__exclude_urls:
if url in self.data.get('re_url'):
return response
if response.get('accepted_media_type') == 'application/json':
# 获取响应数据字符串(多用于API, 返回JSON字符串)
rp_content = response.content.decode()
else:
rp_content = '不是json数据'
self.data['rp_content'] = rp_content
self.data['re_user'] = request.user.username if request.user else 'AnonymousUser' # 操作人(需修改),网站登录用户
# 耗时
self.end_time = time.time() # 响应时间
access_time = self.end_time - self.start_time
self.data['access_time'] = round(access_time * 1000) # 耗时毫秒/ms
OpLogs.objects.create(**self.data) # 操作日志入库db
return response
3.django中添加中间件
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'utils.jwt1.JwtAuthorizationMiddleware', # 通过Authorization请求头传递token
'utils.middlewares.LogMiddleware.OpLog', # 操作日志
'utils.middlewares.Exception.AllException' # 全局异常
]
四、全局异常中间件
1.新建Exception.py文件
# -*- coding:utf-8 _*-
"""
@author:lenovo
@file: Exception.py.py
@time: 2023/4/23 18:20
"""
import logging
from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
logger = logging.getLogger("app")
class AllException(MiddlewareMixin):
def process_exception(self, request, exception):
"""
视图函数报错后
:param request: 请求对象
:return:
"""
print(exception)
logger.error(exception)
ex_data = {
"msg": "Sorry, we make a mistake (* ̄︶ ̄)!",
"code": 1000,
"request": request.path,
'data': []
}
return JsonResponse(data=ex_data, status=500)
2.django配置添加异常中间件
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'utils.jwt1.JwtAuthorizationMiddleware', # 通过Authorization请求头传递token
'utils.middlewares.LogMiddleware.OpLog', # 操作日志
'utils.middlewares.Exception.AllException' # 全局异常
]