为了更好的浏览体验,请不要在本页面禁用 Javascript 🙂
2018-09-19
Django
Python

Django在模型层获取用户信息

起因
要做一个统一的log模块,用来存储模型实例的变更记录。既然是log,就要知道是谁操作的。在Django中分为view层和model层。在view层面可以很方面的获取到request信息,但是在model层是获取不到。
搜索了一番,发现了很做骚操作,简要地记录一下。
关键词: django get current user in model/signal
方法一
也是最常见的方法,中间件中获取request信息,保存在当前线程中
from threading import current_thread from django.utils.deprecation import MiddlewareMixin _requests = {} def current_request(): return _requests.get(current_thread().ident, None) class RequestMiddleware(MiddlewareMixin): def process_request(self, request): _requests[current_thread().ident] = request def process_response(self, request, response): # when response is ready, request should be flushed _requests.pop(current_thread().ident, None) return response def process_exception(self, request, exception): # if an exception has happened, request should be flushed too _requests.pop(current_thread().ident, None)
Python
参见
方法二
在pre_save的时候,从堆栈信息中信息中获取request对象。
from django.db.models.signals import pre_save from django.dispatch import receiver @receiver(pre_save) def my_callback(sender, **kwargs): import inspect for frame_record in inspect.stack(): if frame_record[3]=='get_response': request = frame_record[0].f_locals['request'] break else: request = None ...
Python
参见
方法三
单例
中间件中获取到请求用户,存储在单例中。
Build with gatsby,react,material-ui and Copyright 2019 Mayne Powered by gine-blog