It's still not completely clear to me what you're trying to achieve, but it sounds like you might want something like the following.
If you create a piece of middleware in, say...
myproject/myapp/middleware/globalrequestmiddleware.py
...which looks like this...
import thread
class GlobalRequestMiddleware(object):
_threadmap = {}
@classmethod
def get_current_request(cls):
return cls._threadmap[thread.get_ident()]
def process_request(self, request):
self._threadmap[thread.get_ident()] = request
def process_exception(self, request, exception):
try:
del self._threadmap[thread.get_ident()]
except KeyError:
pass
def process_response(self, request, response):
try:
del self._threadmap[thread.get_ident()]
except KeyError:
pass
return response
...then add it into your settings.py
MIDDLEWARE_CLASSES
as the first item in the list...
MIDDLEWARE_CLASSES = (
'myproject.myapp.middleware.globalrequestmiddleware.GlobalRequestMiddleware',
# ...
)
...then you can use it anywhere in the request/response process like this...
from myproject.myapp.middleware.globalrequestmiddleware import GlobalRequestMiddleware
# Get the current request object for this thread
request = GlobalRequestMiddleware.get_current_request()
# Access some of its attributes
print 'The current value of session variable "foo" is "%s"' % request.SESSION['foo']
print 'The current user is "%s"' % request.user.username
# Add something to it, which we can use later on
request.some_new_attr = 'some_new_value'
...or whatever it is you want to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…