[Newbie Question] How to maintain a global variable

7 views
Skip to first unread message

Eric

unread,
Apr 14, 2008, 4:26:14 PM4/14/08
to Google App Engine
For some reason, I need to maintain a global variable, e.g. a visitor
counter. Is there a way to do this without involving the database?

Whether the answer is yes or no, can you also scratch few lines of
code to demonstrate howto if the solution is not so that obvious in
the first place? Thanks!

-Eric

Eric

unread,
Apr 14, 2008, 4:27:58 PM4/14/08
to Google App Engine

Duncan

unread,
Apr 15, 2008, 4:14:50 AM4/15/08
to Google App Engine
Here's some sample code though if anyone else is looking:

from functools import wraps
def globalmethod(f):
"""A decorator which creates a classmethod that calls the original
function
inside a transaction with the single Globals object as the first
argument.
"""
@wraps(f)
def wrapper(cls, *args, **kwds):
def inner():
obj = Globals.get_by_key_name(cls.KEY)
if not obj:
obj = cls(key_name=cls.KEY)
result = f(obj, *args, **kwds)
obj.put()
return result
return db.run_in_transaction(inner)
return classmethod(wrapper)

class Globals(db.Model):
KEY = "globalvars"
visitors = db.IntegerProperty(default=0)

@globalmethod
def countVisitor(self, n=1):
self.visitors += n
return self.visitors

then to use it:

visitorCount = Globals.countVisitor()

which increments the counter and returns the new value (call
countVisitor(0) if you just want to access it without changing it).

Extend the class as required to hold other values, remember that any
access to values should be protected by a transaction, so use the
decorator to wrap up related updates to globals in a single method.

Aaron Krill

unread,
Apr 15, 2008, 4:33:44 AM4/15/08
to google-a...@googlegroups.com
If you are wanting this to never change ever I'd use datastore. Just create a Globals model with key and value properties, and update them whenever. That way the data is persistent between processes and updates. Otherwise the globals will disappear when you update the codebase.

Ben the Indefatigable

unread,
Apr 15, 2008, 7:50:25 PM4/15/08
to Google App Engine
Aaron, the example you quoted does use the datastore.
Reply all
Reply to author
Forward
0 new messages