-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmiddleware.py
65 lines (50 loc) · 2.19 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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)
class LocalUserMiddleware(object):
def process_request(self, request):
# request.user closure; asserts laziness; memoization is implemented in
# request.user (non-data descriptor)
_do_set_current_user(lambda self: getattr(request, 'user', None))
# 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
# from django.conf import settings
# USER_ATTR_NAME = getattr(settings, 'LOCAL_USER_ATTR_NAME', '_current_user')
# try:
# from threading import local
# except ImportError:
# from django.utils._threading_local import local
# _thread_locals = local()
# from new import instancemethod
# def _do_set_current_user(user_fun):
# setattr(_thread_locals, USER_ATTR_NAME, instancemethod(user_fun, _thread_locals, type(_thread_locals)))
# def _set_current_user(user=None):
# '''
# Sets current user in local thread.
# Can be used as a hook e.g. for shell jobs (when request object is not
# available).
# '''
# _do_set_current_user(lambda self: user)
# class LocalUserMiddleware(object):
# def process_request(self, request):
# # request.user closure; asserts laziness; memoization is implemented in
# # request.user (non-data descriptor)
# _do_set_current_user(lambda self: getattr(request, 'user', None))
# def get_current_user():
# current_user = getattr(_thread_locals, USER_ATTR_NAME, None)
# return current_user() if current_user else current_user