python - django-mptt:处理并发插入

标签 python django django-mptt

我有一个线程评论系统,在 99.9% 的时间里都可以正常工作,但偶尔树会崩溃,左/右值会重复。

我发现当两个帖子同时发生时(彼此相隔不到一秒)会发生这种情况,并且大概发生的情况是第二个帖子在第一个之前更新树的左/右值完成了。

我在 views.py 中的评论插入代码如下:

@login_required
@transaction.autocommit
def comment(request, post_id):
    parent = get_object_or_404(Post, pk=post_id)

    if request.method == 'POST':
        form = PostForm(request.POST)

        form.parent = post_id
        if form.is_valid():
            new_post = newPost(request.user, form.cleaned_data['subject'], form.cleaned_data['body'])
            new_post.insert_at(parent, 'last-child', save=True)
            return HttpResponseRedirect('/posts/')
    else:
        form = PostForm()

    return render_to_response('posts/reply.html', {'requestPost': request.POST, 'form': form, 'parent': parent}, context_instance=RequestContext(request))

处理这个问题的正确方法是什么?有没有一种 django 方法可以确保在第一个数据库事务完成之前不会调用第二个 View ?或者我应该在每次插入后重建树以确保完整性?或者是否有更好的插入方法可供使用?

谢谢!

编辑:我正在使用 MySQL。

最佳答案

transaction.autocommit() 是标准的 django 行为。如果没有重新定义全局事务行为,你的装饰器什么都不做。 使用应该使用 commit_on_success() 装饰器。 View 中的所有数据库操作都将在一个事务中。 您可以在 https://docs.djangoproject.com/en/1.5/topics/db/transactions/ 上阅读更多内容

PS:django 1.6 中事务管理会更新,注意。

关于python - django-mptt:处理并发插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19593781/

相关文章:

python - 无法打开 urllib2 中的某些 url,但仍可以在浏览器中打开?

python - 您如何确定 matplotlib 正在使用哪个后端?

python - 如何确定国际化参数的优先级

django - 如何对 Django-CMS 扩展进行单元测试?

sql - 即使深度在 3 - 4 左右,MPTT 对于维护像数据库这样的树是否有点矫枉过正?

python - Pandas:将多个 DataFrame 导出到多个 xlsx 文件

python - 无法使用 errbot 命令创建聊天室,导致 not_allowed_token_type 错误

python - Django 和 Yubikey 集成

python - 如何在 Django REST 中序列化层次关系

django - 导入错误 : cannot import name MPTTModel