Created
June 28, 2018 14:43
-
-
Save jmasonherr/2449ea65218b2b0d9e03b04e98bfb06b to your computer and use it in GitHub Desktop.
Get current user from anywhere in Django 2.x with middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import absolute_import, division, print_function | |
try: | |
from threading import local | |
except ImportError: | |
from django.utils._threading_local import local | |
_thread_locals = local() | |
def get_current_request(): | |
""" returns the request object for this thread """ | |
return getattr(_thread_locals, "request", None) | |
def get_current_user(): | |
""" returns the current user, if exist, otherwise returns None """ | |
request = get_current_request() | |
if request: | |
return getattr(request, "user", None) | |
def thread_local_middleware(get_response): | |
# One-time configuration and initialization. | |
def middleware(request): | |
# Code to be executed for each request before | |
# the view (and later middleware) are called. | |
_thread_locals.request = request | |
response = get_response(request) | |
# Code to be executed for each request/response after | |
# the view is called. | |
if hasattr(_thread_locals, "request"): | |
del _thread_locals.request | |
return response | |
return middleware |
Hi, excuseme
How should I register this middleware?
add this to settings.MIDDLEWARE : thread_local_middleware
MIDDLEWARE =['path_to_.thread_local_middleware']
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, excuseme
How should I register this middleware?