python - Django Middleware context handling issue related to variable domain -


i face weird variable domain issue when trying define middleware django keep request in thread context. first code section create error when try access method "get" api in views file. second code example works great. why???

example 1 (does not work):

class contexthandler(object):     #_locals = threading.local()      def process_request(self, request):         self._locals = threading.local()         self._locals.x = "alon"         return none 

example 2 (works):

class contexthandler(object):     _locals = threading.local()      def process_request(self, request):         self._locals.x = "alon"         return none 

common method:

@classmethod     def get(cls):         return getattr(cls._locals, 'x', none) 

thanks!

in first example have no class property _locals, instance property. in first case contexthandler._locals none , cls in get() contexthandler.

if want thread safe code don't stick @classmethod and

class contexthandler(object):     _locals = threading.local() 

as far know class definition processed once (most in main thread). i'd rather initialize _locals in process_request() , make get() instance method:

class contexthandler(object):      def process_request(self, request):         self._locals = threading.local()         self._locals.x = "alon"         return none      def get(self):         return getattr(self._locals, 'x', none) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -