1

I have a Django project that uses a pretty complex object which I would like to pass around in views. Now, normally one would use the session variables for that:

request.session['variable'] = complex_object

I am aware that this is the normal way to do this. Alas, my very complex object is not JSON serializable so I cannot save it as a session variable. One way to solve this would be to write a serializer for the object. But since the object is really horribly complex and nested, this is not even tedious: it's impossible.

So I was searching for an easier workaround. I started working with global variables. This is bad practice, I know, but I need a solution. Global variables work very well in development. But as soon as I deploy the project, they start becoming very unreliable. Sometimes they work, sometimes they don't. So this can't be the way either.

To not make this question too text heavy, some pseudo code to show you my global variables in principle:

global p

def a(request):
   global p
   p = 5

def b(request):
   global p
   print(p)

As I said, doing this in development works well. In production, not so much.

Any ideas? I'd even be game for a dirty hack by now.

Edit: Pickling the object will not work, as it is a SwigPyObject and these do not work with pickle.

7
  • Two immediate problems I can see with global variables are: i) requests from different users would be modifying the same value and ii) the value wouldn't survive a restart. You could use a value in the user's session to look up the object in a dictionary but then you have to make sure that a user can't modify that value and fetch someone else's object and you still have to figure out how to persist the data.
    – Kemp
    May 4, 2021 at 9:27
  • Yes, but the dictionary would have to be in some form global too, right? Because otherwise I cannot access it in different views of my Django project
    – TimoSan
    May 4, 2021 at 9:29
  • Global variables of course won't work with a web server. If you really can't store data in the database or in the session, all I can think of is using the pickle module, and saving the pickled object to a file. To keep track of which file is for which user, save it to the database using a file field or save the file name in a session variable. May 4, 2021 at 9:29
  • Probably the PickleSerializer will help.
    – sur0k
    May 4, 2021 at 9:30
  • Also if that object is system-wide (not session-wide), you can set that up in the settings module.
    – sur0k
    May 4, 2021 at 9:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.