Search code examples
pythonturbogears2

function to be called every page request


I am looking for a way to log user activity on my site. I've got a standart TG2 quickstart project. "User" class in my model has additional column:

class User(DeclarativeBase):
...
    last_activity = Column(DateTime)
...

...and i have a function:

def update_activity():
    if 'REMOTE_USER' in request.environ:
        auser = DBSession.query( User ).filter( User.user_name==request.environ['REMOTE_USER'] ).one()
        auser.last_activity = datetime.now()

I don't know where to place this function. I need it to be called each time any page of my server is visited. Inside RootController it is only executed once.


Solution

  • To perform some actions before and after every method of a controller you can define _before and _after methods inside the controller class.

    If you need to have them performed before and after every method in the application you can call base_config.register_hook('before_render' function) inside app_cfg.py to register an application wide hook.