我仍然不完全清楚您要达到的目标,但听起来您可能想要以下内容。
如果您在其中创建一个中间件,例如...
myproject/myapp/middleware/globalrequestmiddleware.py
...看起来像这样...
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
...然后将其settings.py
MIDDLEWARE_CLASSES
作为列表中的第一项添加到您的...
MIDDLEWARE_CLASSES = (
'myproject.myapp.middleware.globalrequestmiddleware.GlobalRequestMiddleware',
# ...
)
...然后您可以像这样在请求/响应过程中的任何地方使用它...
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'
......或者你想做的任何事情。