1. 新增middleware.py中间件: 需要在setting.py注册
class LoggingMiddleware: """ 日志记录模块: 操作用户、操作ip、请求路径、请求方式、请求时间 """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if forwarded_for: # 以逗号为分隔符,获取最后一个IP地址 request.internal_ip = forwarded_for.split(',')[-1].strip() else: request.internal_ip = request.META.get('REMOTE_ADDR') if not request.path.startswith("/v5/account/login/") and not request.user.is_authenticated \ or request.method not in ['POST', 'PUT', 'PATCH', 'DELETE']: return response print("request.user: ", request.user) print("request.path: ", request.path) print("request.method: ", request.method) print("request.ip: ", request.internal_ip) print("status_code: ", response.status_code) return response
2. 新增model.py
class LogModel(BaseModel): """系统操作日志记录""" request_user = models.CharField(max_length=32, blank=True, verbose_name="请求用户") request_path = models.CharField(max_length=128, blank=True, verbose_name="请求路径") request_method = models.CharField(max_length=8, blank=True, verbose_name="请求方式") request_ip = models.CharField(max_length=32, blank=True, verbose_name="请求ip") response_code = models.CharField(max_length=8, blank=True, verbose_name="响应码") class Meta: verbose_name = "系统操作日志" verbose_name_plural = verbose_name
还有基于信号实现的(监听某张表的操作)
还有基于django-simple-history的操作。但是这种操作会额外新增一张表(比如你原本有100张表。使用了这个插件会额外生成100张。总共就是200张)
第一种方式最为简洁。代码量更少。可维护性更高(也可以将ContentType表添加进去)
contenttype配置示例
models配置示例
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation class RechargePackage(BaseModel): """ 充值描述 """ total_fee = models.BigIntegerField(verbose_name="订单的资金总额,单位为分") count = models.BigIntegerField(verbose_name='充值次数') description = models.CharField(max_length=256, verbose_name="商品描述") shopping_car_list = GenericRelation("ShoppingCar") class ShoppingCar(BaseModel): product_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING, related_name='product_order_list') product_id = models.CharField(max_length=32) product = GenericForeignKey('product_type', 'product_id') count = models.IntegerField(verbose_name='数量')
标签:name,记录,models,request,django,length,日志,response,verbose From: https://www.cnblogs.com/52-qq/p/17296274.html