How to pass variables between different view functions in Django

时间:2015-10-30 21:57:18

标签: python django

Some variables (class object) needs to be shared among different view functions. Each view function changes this object's properties. This object is user-specific, that is to say, user needs to log in the web page, then access different webpage. I do not want different users share/change this object variable. What I can think of is:

  1. Using global to declare a variable in different view functions. However, in it is running in Django runserver with multi-threaded, when multiple users access it, will the global variables be changed/shared by all users? or this variable is specific to each user?

  2. Using session, however, the variable is object, which is not json serializable.

  3. Store it in database, however, this is object and it is not allowed to store in the database. I cannot pickle it either.

What is the correct way of sharing variables among different view functions while allowing multiple users access server concurrently?

Thanks,

This is the problem I met. Please just explain a little bit, please do not just down vote without any comment, thank you

1 个答案:

答案 0 :(得分:1)

You say the object is user-specific. Is it also session-specific? If the user were to open a new tab in his browser and access another page in your app, could he have two different objects? If so, then it makes sense to store it in the session. You can use pickle serialization to get around JSON (although it can lead to insecurities, if the object is user-provided.)