python - Is there a way to access the context from everywhere in Django? -


i'm looking way have global variable accessible module within django request without having pass around parameter. traditionally in other mvcs, store in request context or session , access context "get_current_context" method (which couldn't find in django).

is there this, or other mechanism allow me have value available anywhere in request context?

tia!

update: research has come 1 viable solution - thread locals (some argue it's not viable, there's pretty active discussion it, pros , cons , seems people think should able use in django, if responsibly).

it's still not clear me you're trying achieve, sounds might want following.

if create piece of middleware in, say...

myproject/myapp/middleware/globalrequestmiddleware.py 

...which looks 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 settings.py middleware_classes first item in list...

middleware_classes = (     'myproject.myapp.middleware.globalrequestmiddleware.globalrequestmiddleware',     # ... ) 

...then can use anywhere in request/response process this...

from myproject.myapp.middleware.globalrequestmiddleware import globalrequestmiddleware  # current request object thread request = globalrequestmiddleware.get_current_request()  # access of attributes print 'the current value of session variable "foo" "%s"' % request.session['foo'] print 'the current user "%s"' % request.user.username  # add it, can use later on request.some_new_attr = 'some_new_value' 

...or whatever want do.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -