tags:

views:

108

answers:

1

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

Thanks

something like

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

+1  A: 

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.

nosklo
Thanks, If I have another application accessing this counter, will it automatically be updated ? Say counter = 0 in settings.py, in webpage1.py counter += 1, when I import this counter in other application, it equals 0 or 1 ?
It seems I have to use models.py to save the counter in database, I'm not sure if there is other better way.
if you do "settings.counter += 1" then it will be updated for the current process.
nosklo