質問

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.

役に立ちましたか?

解決

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.

他のヒント

Here is solution I found using decorators.

...
from tg.decorators import before_call
...
def updateactivity(*l, **kw):
    now = datetime.now()
    DBSession.query( User ).filter( User.user_name==request.environ['REMOTE_USER']).one().last_activity = datetime(now.year, now.month, now.day, now.hour, now.minute, now.second)
...
class RootController(BaseController):
...
    @expose('myproject.templates.mytemplate')
    @require(predicates.not_anonymous)
    @before_call(updateactivity)
    def mymethod(self, **kw):
...
        return dict(page='mypage')
...

Is there any way to use it for whole controller? Like using "allow_only" for controller instead of "@require" for each method.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top