0

Is there any way to maintain a variable that is accessible and mutable across processes?

Example

User A made a request to a view called make_foo and the operation within that view takes time. We want to have a flag variable that says making_foo = True that is viewable by User B that will make a request and by any other user or service within that django app and be able to set it to False when done

Don't take the example too seriously, I know about task queues but what I am trying to understand is the idea of having a shared mutable variable across processes without the need to use a database.

Is there any best practice to achieve that?

bluesummers
  • 11,365
  • 8
  • 72
  • 108
  • 1
    "... without the need to use a database" -- Why? Using the database seems like the proper solution for this. Alternatively you could use a file-based lock, but I don't see a clear benefit, and I'd say the database is easier to use. – knbk May 23 '17 at 19:19
  • database is external to the world of ptyhon and django, its something to poll for. seems to me a better solution is something within the django framework where all the processes live. its more than possible that django itself keeps variables like these to manage the whole thing – bluesummers May 23 '17 at 19:43

1 Answers1

1

One thing you need to be aware of is that when your django server is running in production, there is not just one django process, there will be several worker threads running at the same time.

If you want to share data between processes, even internally, you will need some kind of database to do so, whether that's with SQLite3 or Redis (which I recommend for stuff like this).

I won't go into the details because it's already been said before by other people, but Redis is an in-memory database that uses key-value storing (unlike how Django uses a model, Redis is essentially a giant dictionary). Redis is fast and most operations are atomic which means you are unlikely to encounter race conditions.

Jessie
  • 2,319
  • 1
  • 17
  • 32