django小练习
1.练习1
写一个类,有个name属性,如果name赋值为非字符串,就不让放
urls.py
from django.conf.urls import url from app01 import views urlpatterns = [ url(r'^index/',views.index), ]
views.py
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')
在django的app应用下创建一个py文件,然后自定义一个类,并在settings.py文件中配置上该自定义中间件:
middles.py
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 ''' 在执行request.data = json.loads(request.body)会出现三种情况: 1.请求是urlencoded编码格式,会报错,走except下面的代码, 2.请求是json格式的数据,会被直接解析并封装到request.data中 3.请求是formdata格式的数据,文件数据无法反序列化,也会走except部分 ''' # settings.py配置文件中 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', 'app01.middles.ReqData', # 这里要注册自定义的中间件 ]
参考:Django中间件小实例