user178845
user178845

Reputation:

global counter in Django Application?

I was wondering if there is "global counter" in Django application, like the way I store "global counter" in Servlet Context scope in Tomcat.

something like

getServletContext().getAttribute("counter"); counter++;

Upvotes: 0

Views: 1294

Answers (1)

nosklo
nosklo

Reputation: 223032

When you write a django application (or any wsgi application, for that matter), you don't know beforehand if your application will end up running standalone on a single server, or multithreaded, or multiprocessed, or even in multiple separate machines as part of a load balancing strategy.

If you're going to make the constraint "my application only works on single-process servers" then you can use something like this:

from django import settings
settings.counter += 1

However that constraint is often not feasible. So you must use external storage to your counter.

If you want to keep it on memory, maybe a memcached

Maybe you just log the requests to this view. So when you want the counter just count the number of entries in the log.

The log could be file-based, or it could be a table in the database, just define a new model on your models.py.

Upvotes: 1

Related Questions