1đź‘Ť
You should not do this. Your proposed solution is very dangerous, as now all users will share the same data. You almost certainly don’t want that.
For per-user data shared between requests, you should use the session.
Edit
There’s no way to know if they are separate processes or not. Your server software (Apache, or whatever) will determine the number of processes to run (based on your settings), and automatically route requests between them. Each process could serve any number of requests before being killed and restarted. So, in all likelihood, two consecutive requests could indeed be served by the same process, in which case the data will indeed collide.
Note that the session data is stored on the server (only a key is stored in the user’s cookie), so size shouldn’t be a consideration. See the sessions documentation.
1đź‘Ť
You should not want to do that.
But it works as “expected”: just do
mymodule.variable = value
anywhere in your code.
So, yes, your example code is setting the variable in the current running program –
but then you hit the part where I said: “you should not want to do that” 🙂
Because django, when running with production settings will behave differently than a single-proccess, single-thread python application.
In this case, if the variable is not set in mymodule
when you try to access it later, it maybe because this access is happening in another process entirely (thus, “global variables” (actually, in Python we have “module” variables) won’t work, since they are set per process).
In this particular case, since you have a function ot retrieve your desired value,and you may be worried that it is an expensive value, you should memoize it – check the documentation on django.utils.functional.memoize (which will change to django.utils.lru_cache.lru_cache in upcoming versions) – https://docs.djangoproject.com/en/dev/releases/1.7/ – this way it will be called once per process in your application as it serves from separated processes.
- [Answer]-WritableField field_from_native returned value not used in Serializer
- [Answer]-Django AbstractUser Not Allowing Field Data To Be Saved
- [Answer]-Modify UpdateView Form Data Before Presenting To User
-1đź‘Ť
My solution (for now):
In the module mymodule.py, I initialized a dictionary: data = {}
Then in my get()
method:
if not ('user' in mymodule.data):
mymodule.data['user'] = mymodule.get_user_data()
Subsequently, I’m able to retrieve the mymodule.data['user']
object in the post()
method (and presumably elsewhere in my code). Seems to work but please let me know if it’s an aberration!
- [Answer]-Can I use jQuery.post() with LiveServerTestCase?
- [Answer]-Displaying "info" by selecting foreign key in django admin
- [Answer]-Autoreload does not work in Celery
- [Answer]-Combine a list of dictionaries ; specific use case