Created
November 14, 2017 01:04
-
-
Save vparitskiy/71bb97b4fd2c3fbd6d6db81546622346 to your computer and use it in GitHub Desktop.
get Django request everywhere using threading.local
This file contains 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
# -*- coding: utf-8 -*- | |
import logging | |
from threading import local | |
from django.contrib.auth.models import AnonymousUser | |
_thread_locals = local() | |
logger = logging.getLogger(__name__) | |
def set_current_request(request): | |
""" | |
Binds the request to the current thread. | |
:param request: Django request object | |
:return: | |
""" | |
logger.debug(u"Save request in current thread") | |
return setattr(_thread_locals, '__django_userforeignkey__current_request', request) | |
def get_current_request(): | |
""" | |
Gets the request from the current thread. | |
:return: Django request object | |
""" | |
return getattr(_thread_locals, '__django_userforeignkey__current_request', None) | |
def get_current_user(): | |
""" | |
Gets the current user from the current request. In case there is no current | |
request, or there is no user information attached to the request, an AnonymousUser object | |
is returned. | |
:return: User object | |
""" | |
request = get_current_request() | |
if not request or not hasattr(request, 'user'): | |
return AnonymousUser() | |
return request.user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment