亲宝软件园·资讯

展开

Django怎样简单快速实现PUT、DELETE方法

人气:3

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

$.ajax({
  url: 'XXX',
  type: 'PUT',
  dataType: 'json',
  data: {
    's': $("#select-id").find("option:selected").text()
  },
  success: function (data) {
    console.log('ok');
  }
})
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

很不幸,在默认情况下,我们不能很轻易的根据restful来写url,但是,懒癌的威力是无穷大的!机智的小北方通过查阅资料以及自定义修改实现了使用中间件来达成次目的

首先我们需要在django里某个app下添加一个中间件py文件,命名随意,这里我叫middleware

#!/usr/bin/env python
# -*- coding:utf8 -*-
# __author__ = '北方姆Q'

from django.http import QueryDict
try:
  from django.utils.deprecation import MiddlewareMixin  # 1.10.x
except ImportError:
  MiddlewareMixin = object                # 1.4.x-1.9.x


class HttpPost2HttpOtherMiddleware(MiddlewareMixin):
  def process_request(self, request):
    """
    可以继续添加HEAD、PATCH、OPTIONS以及自定义方法
    HTTP_X_METHODOVERRIDE貌似是以前版本的key???
    :param request: 经过原生中间件处理过后的请求
    :return:
    """
    try:
      http_method = request.META['REQUEST_METHOD']
      if http_method.upper() not in ('GET', 'POST'):
        setattr(request, http_method.upper(), QueryDict(request.body))
    # except KeyError:
    #   http_method = request.META['HTTP_X_METHODOVERRIDE']
    #   if http_method.upper() not in ('GET', 'POST'):
    #     setattr(request, http_method.upper(), QueryDict(request.body))
    except Exception:
      pass
    finally:
      return None

然后在django的settings里注册此中间件就好了

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.middleware.common.CommonMiddleware',
  'django.middleware.csrf.CsrfViewMiddleware',
  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'yourappname.middleware.HttpPost2HttpOtherMiddleware',              # 改成自己的app名称哦
]
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论