[Answer]-Django implementing simple vistor log

1👍

First off, I assume you don’t have access to the apache (or whatever host is running your django app) logs and/or you want to eventually add other things and/or you want it available in the database, as otherwise, you can skip a lot of work and just grep the logs.

Anyways, I’d recommend rewriting track to work as a decorator (and adjust log as you need it… note that I believe you can get the URL from the request object versus passing it in as a page value in case you want to know which specific instance was visited). There are also ways you could probably do this with middleware, but this gives you a pretty good mix of simplicity and ability to control which views get logged.

To borrow an example from http://www.djangofoo.com/253/writing-django-decorators

def track(page):
    def decorator(func):
        def inner_decorator(request, *args, **kwargs):
            log(request, page)
            return func(request, *args, **kwargs)
        return wraps(func)(inner_decorator)
    return decorator

And then in your urls (or you can also do @track to decorate function based views)

url(r'^(?P<page>\d+)?/?$', track("index")(PostListView.as_view(
        model=Post,
        paginate_by=3,
        ))),
url(r'^someregexp$', track("pagename")(SomeListView.as_view(
        model=Post,
        paginate_by=3,
        ))),

Edit: meant to add. Do note that in general, GET requests are supposed to be idempotent; logging is a gray area but the main thing to keep in mind is that some requests may not get logged as you might expect if the page is cached (for Posts this shouldn’t be an issue)

👤Foon

Leave a comment