Reputation: 1506
This sounds nasty. I want to set a global variable in the request, which means all my views can refer to that constant by doing:
getattr(request, 'CONSTANT_NAME', None)
However, this variable's value may be changed at some point, which means I have the following code in one of my view:
setattr(request, 'CONSTANT_NAME', VALUE)
I know the way I am doing this is definitely wrong, but I wish to know if there is a correct and clean way to achieve what I am looking for.
I am thinking about middleware, but not sure how to do it. A hint is sufficient.
Thanks in Advance.
UPDATE: Someone mentioned about Session. I pretty sure it should works. However, it is not clean enough. By using session, I need to create same constant as many times as the total number of sessions server maintaining. In fact, the constant remain the same cross the server and it has to be mutable! The last requirement is the nasty part.
Upvotes: 2
Views: 86
Reputation: 1506
Eventually, I took the way of Middleware. I wrote a custom middleware and set a variable in the middleware, something like,
CONSTANT_NAME = None
It is global. And a local thread:
_thread_local = threading.local()
which is also global.
Then I have two methods in the middleware,
def get_constant_value()
return getattr(_thread_local, 'CONSTANT_NAME', None)
def set_constant_value(value):
CONSTANT_NAME = value
which can be called from any views.
Then inside my middleware, I have
def process_request(self, request):
_thread_local.CONSTANT_NAME = CONSTANT_NAME
At this point, I call set and get this server-crossed variable from any view I want.
The solution is not perfect (I believe). If anyone got a better idea, let me know please!
Thanks!
Upvotes: 1