使用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名称哦
]

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!