开发者

Keeping track of how many views an object receives in Django

For statistical purposes, I need to keep a log of each time a certain instance of a Model is viewed in Django. I started off by creating a separate model, Stats, that contains a ManyToMany field to another Model that stores the date and time of the access. Every time the object is accessed in a view, I update the associated Stats object.

There are 2 problems with this approach (if not more):

  1. It violates the principle of not writing any data on a GET request.
  2. More importantly, it's really slow, especially because several objects can be viewed at once. This results in a visible开发者_如何学运维 delay when the page is loaded.

So my question is, is there a better way of doing this? If not, what techniques are available to speed things up, such as delayed writes to the DB? I've never worked with that kind of thing in Django, so any advice would be appreciated.


Right, well, it seems Celery looks like a good option.


Don't worry about (1). Wikipedia says:

Safe methods Some methods (for example, HEAD, GET, OPTIONS and TRACE) are defined as safe, which means they are intended only for information retrieval and should not change the state of the server. In other words, they should not have side effects, beyond relatively harmless effects such as logging, caching, the serving of banner advertisements or incrementing a web counter. Making arbitrary GET requests without regard to the context of the application's state should therefore be considered safe.

I would say keeping a count of views counts as 'mostly harmless'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜