Django中间件小实例

需求:利用django中间件,当普通的键值对数据进来的时候,都能通过request.data中拿到

实现:

1.在子应用下创建一个py文件,自定义一个中间件,自定义中间件需要继承MiddlewareMixin的类,
2.在该类下用process_request方法对进来的数据封装到request.data中
3.在settings.py配置文件中注册自己书写的自定义中间件

middles.py

from django.contrib.auth.middleware import AuthenticationMiddleware
from django.utils.deprecation import MiddlewareMixin
import json

class ReqData(MiddlewareMixin):
    def process_request(self, request):
        try:
            request.data = json.loads(request.body)
        except Exception as e:
            request.data = request.POST
# 这里有三种情况:
1.当提交的数据是json格式的时候,直接被request.body接收,json传的数据格式为字典格式,直接反序列化,不会捕获异常

2.当提交数据格式是urlencoded编码格式时,不是字典格式数据,捕获异常,直接将request.POST中的数据赋值给request.data,

3.如果是文件数据,也无法直接反序列化,直接跟步骤2一样,捕获异常,直接将request.POST中的数据赋值给request.data

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/',views.index)
]

views.py

from django.shortcuts import render,HttpResponse

# Create your views here.

def index(request):
    if request.method == 'POST':
        print('post的值',request.POST)
        print('body的值:',request.body)
        print('data的值:',request.data)
        return HttpResponse('ok')
    print('data的get值:',request.data)
    return render(request,'index.html')

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    {% load static %}
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <link rel="stylesheet" href="{% static 'bootstrap-3.4.1-dist/css/bootstrap.min.css' %}">
    <script src="{% static 'bootstrap-3.4.1-dist/js/bootstrap.min.js' %}"></script>
</head>
<body>
<form action="" method="post">
    <p>用户名:<input type="text" name="username" id="id_username"></p>
    <p>密码:<input type="text" name="pwd" id="id_pwd"></p>
    <input type="submit" value="提交1">
    <input type="button" value="提交" id="id_btn">
</form>
<script>
    $('#id_btn').click(function (){
        $.ajax({
            url:'',
            type:'post',
            contentType:'application/json',
            data:JSON.stringify({'username':$('#id_username').val(),'pwd':$('#id_pwd').val()}),
            success:function (){
                alert('ok')
            }
        })
    })
</script>
</body>
</html>

 

posted @ 2022-04-26 23:37  _yessir  阅读(73)  评论(0编辑  收藏  举报