bluesummers
bluesummers

Reputation: 12607

Static variable across processes in django

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?

Upvotes: 0

Views: 613

Answers (1)

Jessie
Jessie

Reputation: 2475

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.

Upvotes: 1

Related Questions