我不明白,为什么只有delete_node不起作用

时间:2018-08-31 12:13:39

标签: python django jstree

以下是来自用户的三个请求geeting,create_node,rename_node运行正常,但delete_node请求未运行。

requests:
[31/Aug/2018 17:00:53] "GET /buildknowledge/?operation=create_node&id=1&text=New+node HTTP/1.1" 200 16071
[31/Aug/2018 17:01:10] "GET /buildknowledge/?operation=rename_node&id=63&text=pkkkk HTTP/1.1" 200 16071
[31/Aug/2018 17:02:33] "GET /buildknowledge/?operation=delete_node&id=63 HTTP/1.1" 200 16071

views.py:

def basetest(request):
     cu_id = request.user.id
     if 'operation' in request.GET and "id" in request.GET and "text" in request.GET:
       operation = request.GET['operation']
       pid=request.GET['id']
       nodename=request.GET['text']
       if "create_node" == operation:
          p=Buildkb4.objects.create    (parent=pid,created_by=cu_id,text=nodename)
          p.save()
       elif "delete_node" == operation:
           Buildkb4.objects.filter(pk=pid).delete()
       elif "rename_node" == operation:
           Buildkb4.objects.filter(pk=pid).update(text=nodename)
   return render(request,"registration/basetest.html")

1 个答案:

答案 0 :(得分:0)

  

注意:使用GET请求执行副作用(例如更新或删除数据库中的记录)不是一个好主意。因此,我建议将此类请求更改为POST,DELETE或PATCH。更多信息在这篇文章的底部。

根据显示的日志,删除调用在 querystring 中带有两个参数:operationid。但是第一个if语句也需要一个text参数:

def basetest(request):
     cu_id = request.user.id
     if 'operation' in request.GET and "id" in request.GET and "text" in request.GET:
       operation = request.GET['operation']
       pid=request.GET['id']
       nodename=request.GET['text']
       if "create_node" == operation:
          p=Buildkb4.objects.create    (parent=pid,created_by=cu_id,text=nodename)
          p.save()
       elif "delete_node" == operation:
           Buildkb4.objects.filter(pk=pid).delete()
       elif "rename_node" == operation:
           Buildkb4.objects.filter(pk=pid).update(text=nodename)
   return render(request,"registration/basetest.html")

所以这永远不会达到elif "delete_node" == operation:的情况。

您可以通过减少检查的限制来解决此问题,例如:

def basetest(request):
     cu_id = request.user.id
     if 'operation' in request.GET and "id" in request.GET:
       operation = request.GET['operation']
       pid=request.GET['id']
       if "delete_node" == operation:
           Buildkb4.objects.filter(pk=pid).delete()
       elif 'text' in request.GET:
           nodename=request.GET['text']
           if "create_node" == operation:
               p=Buildkb4.objects.create(parent=pid,created_by=cu_id,text=nodename)
           elif "rename_node" == operation:
               Buildkb4.objects.filter(pk=pid).update(text=nodename)
   return render(request,"registration/basetest.html")

现在它可以工作了。 但是,GET应该没有没有的副作用。因此,您基本上违反了GET请求的合同。

通常,删除是通过POST或DELETE请求执行的,而不是通过GET请求进行的。更改数据也由POST或PATCH请求处理,再次由GET请求处理。通过发出带有副作用的GET请求,机器人(例如搜索引擎)可能会查询URL,并删除和/或更新您的数据。这可能不是您想要的。