Django - 计算模型实例视图(对于“顶部条目”应用程序)
我是新人,也很困惑。 我想创建一个模块来跟踪文章和博客模型的“热门”实例。 我不想触及文章或博客模型的代码。 这是中间件的候选者吗? 查看HttpRequest.path
?
I'm new, and confused. I want to create a module that keeps track of the "top hit" instances of both an article and a blog model. I don't want to touch the code for the article or blog models. Is this a candidate for middleware? looking at the HttpRequest.path
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 request.path 的中间件很丑陋,因为它引入了对用于显示文章和博客文章的 URL 模式的详细信息的依赖。 如果您不介意这种耦合,那么您不妨保存性能影响并在网络服务器日志文件上进行分析。 (编辑:查看中间件 将是一个更好的选择,因为它为您提供了可调用的视图及其参数,我仍然更喜欢装饰器方法,因为它不会在不相关的视图上产生任何开销,但如果您不想触及 URLconf,则视图中间件可以工作。对于博客/文章应用程序)。
我会使用一个视图装饰器来包裹 object_detail 视图(或您的自定义等效视图)。 您可以直接在 URLconf 中进行此包装。 像这样的东西:
你可以在views.py中应用它:
或者在你的URLconf中:
Middleware looking at request.path is ugly, as it introduces a dependency on the details of the URL patterns you use to display articles and blog posts. If you don't mind this coupling, then you might as well just save the performance hit and do your analysis on webserver log files. (EDIT: view middleware would be a better option, as it gives you the view callable and its args. I'd still prefer the decorator approach as it incurs no overhead on unrelated views, but view middleware would work if you don't want to touch the URLconf for the blog/article applications).
I'd use a view decorator that you wrap around the object_detail view (or your custom equivalent). You can do this wrapping directly in the URLconf. Something like this:
And you can apply it in views.py:
or in your URLconf:
你可以在你的 view.py 中创建一个通用的命中模型,
你编写这个函数:
并且你感兴趣的视图返回
这种方法给你的能力,不仅可以计算命中,还可以按时间过滤命中历史记录,内容类型等等...
由于命中表可能会快速增长,因此您应该考虑删除策略。
you could create a generic Hit model
in your view.py you write this function:
and the views that you are interested in return
This approach gives you the power, not only to count the hit, but to filter the hit-history by time, contenttype and so on...
As the hit-table might be growing fast, you should think about a deletion strategy.