对我来说,您仍想达到的目标尚不完全清楚,但听起来您可能想要以下内容。
如果您在其中创建一块中间件,请说…
myproject/myapp/middleware/globalrequestmiddleware.py
看起来像这样
import threadclass 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 threadrequest = GlobalRequestMiddleware.get_current_request()# Access some of its attributesprint '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 onrequest.some_new_attr = 'some_new_value'
…或您想要做什么。



