我是新人,很困惑。我想创建一个模块来跟踪文章和博客模型的“热门”实例。我不想触摸文章或博客模型的代码。这是中间件的候选者吗?看HttpRequest.path
?
答案 0 :(得分:1)
查看request.path的中间件很难看,因为它引入了对用于显示文章和博客帖子的URL模式的详细信息的依赖性。如果您不介意这种耦合,那么您也可以保存性能命中并对Web服务器日志文件进行分析。 (编辑:view middleware将是一个更好的选择,因为它为您提供了可调用的视图及其args。我仍然更喜欢装饰器方法,因为它不会对不相关的视图产生任何开销,但是如果您不想触摸博客/文章应用程序的URLconf,则可以查看中间件。
我会使用一个视图装饰器来环绕object_detail视图(或你的自定义等效视图)。您可以直接在URLconf中进行此包装。像这样:
def count_hits(func):
def decorated(request, *args, **kwargs):
# ... find object and update hit count for it...
return func(request, *args, **kwargs)
return decorated
您可以在views.py中使用它:
@count_hits
def detail_view(...
或在您的URLconf中:
url(r'^/blog/post...', count_hits(detail_view))
答案 1 :(得分:0)
你可以创建一个通用的Hit模型
class Hit(models.Model):
date = models.DateTimeFiles(auto_now=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
在你的view.py中你写这个函数:
def render_to_response_hit_count(request,template_path,keys,response):
for key in keys:
for i in response[key]:
Hit(content_object=i).save()
return render_to_response(template_path, response)
以及您有兴趣返回的观点
return render_to_response_hit_count(request, 'map/list.html',['list',],
{
'list': l,
})
这种方法不仅可以计算命中数,还可以按时间,内容类型等来过滤命中历史记录...
由于命中表可能会快速增长,您应该考虑删除策略。