我是新人,也很困惑。我想创建一个模块来跟踪文章和博客模型的“热门”实例。我不想接触文章或博客模型的代码。这是中间件的候选者吗?查看HttpRequest.path
发布于 2009-05-21 02:05:04
中间件看起来很丑陋,因为它引入了对用于显示文章和博客文章的request.path模式细节的依赖。如果您不介意这种耦合,那么您不妨将性能影响保存下来,并对well服务器日志文件进行分析。(编辑:view middleware将是更好的选择,因为它为您提供了视图callable及其参数。我仍然更喜欢装饰器的方法,因为它不会在无关的视图上产生开销,但是如果你不想接触博客/文章应用程序的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))发布于 2009-05-30 23:32:44
你可以创建一个通用的点击模型
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,
})这种方法不仅可以计算命中次数,还可以根据时间、内容类型等过滤命中历史记录。
由于命中表可能增长很快,您应该考虑删除策略。
https://stackoverflow.com/questions/888905
复制相似问题