36 lines
1.0 KiB
Python
36 lines
1.0 KiB
Python
"""Make the request object available everywhere (e.g. in model instance or signals)."""
|
|
from threading import local
|
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
|
|
|
|
|
_thread_locals = local()
|
|
|
|
|
|
def get_current_request():
|
|
"""Return the request object for this thread."""
|
|
return getattr(_thread_locals, "request", None)
|
|
|
|
|
|
def get_current_user():
|
|
"""Return current user, if exist, otherwise return None."""
|
|
request = get_current_request()
|
|
if request:
|
|
return getattr(request, "user", None)
|
|
|
|
|
|
class ThreadLocalMiddleware(MiddlewareMixin):
|
|
"""Simple middleware that adds the request object in thread local storage."""
|
|
|
|
def process_request(self, request):
|
|
_thread_locals.request = request
|
|
|
|
def process_response(self, request, response):
|
|
if hasattr(_thread_locals, 'request'):
|
|
del _thread_locals.request
|
|
return response
|
|
|
|
def process_exception(self, request, exception):
|
|
if hasattr(_thread_locals, 'request'):
|
|
del _thread_locals.request
|