【Django】处理 PUT 和 DELETE 方法

Posted by 西维蜀黍 on 2019-10-08, Last Modified on 2021-09-21

Context

使用django的小伙伴们应该都知道我们是无法开心的处理PUT和DELETE:

def func(request):
    if request.method == 'GET':
        s = request.GET.get('s', None)
        return XXX
    elif request.method == 'POST':
        s = request.POST.get('s', None)
        return XXX
    elif request.method == 'PUT':
        s = request.PUT.get('s', None)                    # 我们希望愉快的获取继续处理
        return XXX
    elif request.method == 'DELETE':
        s = request.DELETE.get('s', None)                # 我们希望愉快的获取继续处理
        return XXX
    else:
        pass

Solution 1 - 手工解析参数

Django对于PUT/DELETE请求并没有像POST/GET那样有一个字典结构。我们需要手动处理request.body获取参数:

from django.http import QueryDict

if request.method == "PUT":  # Update
    try:
        paras = QueryDict(request.body)
        if "name" in paras:
            name = paras['name']   #or name = paras.get("name")
            Business_Channel.update_channel(id,**{"name":name})

Solution 2 - 实现 middleware

https://www.guguweb.com/2014/06/25/put-and-delete-http-requests-with-django-and-jquery/

Solution 3 - 使用框架

Django REST framework

Reference