Django简单快速实现PUTDELETE方法
Posted 北方姆Q
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django简单快速实现PUTDELETE方法相关的知识,希望对你有一定的参考价值。
使用django的小伙伴们应该都知道我们是无法开心的处理PUT跟DELETE的
1 $.ajax({ 2 url: \'XXX\', 3 type: \'PUT\', 4 dataType: \'json\', 5 data: { 6 \'s\': $("#select-id").find("option:selected").text() 7 }, 8 success: function (data) { 9 console.log(\'ok\'); 10 } 11 })
1 def func(request): 2 if request.method == \'GET\': 3 s = request.GET.get(\'s\', None) 4 return XXX 5 elif request.method == \'POST\': 6 s = request.POST.get(\'s\', None) 7 return XXX 8 elif request.method == \'PUT\': 9 s = request.PUT.get(\'s\', None) # 我们希望愉快的获取继续处理 10 return XXX 11 elif request.method == \'DELETE\': 12 s = request.DELETE.get(\'s\', None) # 我们希望愉快的获取继续处理 13 return XXX 14 else: 15 pass
很不幸,在默认情况下,我们不能很轻易的根据restful来写url,但是,懒癌的威力是无穷大的!emmmmmmm.....
首先我们需要在django里某个app下添加一个中间件py文件,命名随意,这里我叫middleware
1 #!/usr/bin/env python 2 # -*- coding:utf8 -*- 3 # __author__ = \'北方姆Q\' 4 5 from django.http import QueryDict 6 try: 7 from django.utils.deprecation import MiddlewareMixin # 1.10.x 8 except ImportError: 9 MiddlewareMixin = object # 1.4.x-1.9.x 10 11 12 class HttpPost2HttpOtherMiddleware(MiddlewareMixin): 13 def process_request(self, request): 14 """ 15 可以继续添加HEAD、PATCH、OPTIONS以及自定义方法 16 HTTP_X_METHODOVERRIDE貌似是以前版本的key??? 17 :param request: 经过原生中间件处理过后的请求 18 :return: 19 """ 20 try: 21 http_method = request.META[\'REQUEST_METHOD\'] 22 if http_method.upper() not in (\'GET\', \'POST\'): 23 setattr(request, http_method.upper(), QueryDict(request.body)) 24 # except KeyError: 25 # http_method = request.META[\'HTTP_X_METHODOVERRIDE\'] 26 # if http_method.upper() not in (\'GET\', \'POST\'): 27 # setattr(request, http_method.upper(), QueryDict(request.body)) 28 except Exception: 29 pass 30 finally: 31 return None
然后在django的settings里注册此中间件就好了
1 MIDDLEWARE = [ 2 \'django.middleware.security.SecurityMiddleware\', 3 \'django.contrib.sessions.middleware.SessionMiddleware\', 4 \'django.middleware.common.CommonMiddleware\', 5 \'django.middleware.csrf.CsrfViewMiddleware\', 6 \'django.contrib.auth.middleware.AuthenticationMiddleware\', 7 \'django.contrib.messages.middleware.MessageMiddleware\', 8 \'django.middleware.clickjacking.XFrameOptionsMiddleware\', 9 \'yourappname.middleware.HttpPost2HttpOtherMiddleware\', # 改成自己的app名称哦 10 ]
以上是关于Django简单快速实现PUTDELETE方法的主要内容,如果未能解决你的问题,请参考以下文章
ABP PUTDELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词) 引发客户端错误 No 'Access-Control-Allow