解析器
我们都知道源生Django默认只能解析content-type:application/x-www-form-urlencoded头格式的,若果是json格式,form-data格式都要自己处理。
但是在restframework已经为我们做好了,只要配置上,就能帮我们解析请求的数据
举例说明:
表设计:
1 from django.db import models 2 3 4 class UserGroup(models.Model): 5 title = models.CharField(max_length=32) 6 7 8 class UserInfo(models.Model): 9 user_type_choices = ( 10 (1, ‘普通用户‘), 11 (2, ‘vip‘), 12 (3, ‘svip‘), 13 ) 14 user_type = models.IntegerField(choices=user_type_choices) 15 username = models.CharField(max_length=32, unique=True) 16 password = models.CharField(max_length=64) 17 group = models.ForeignKey(‘UserGroup‘, on_delete=models.CASCADE) 18 roles = models.ManyToManyField(‘Role‘) 19 20 21 class UserToken(models.Model): 22 user = models.OneToOneField(to=‘UserInfo‘, on_delete=models.CASCADE) 23 token = models.CharField(max_length=64) 24 25 26 class Role(models.Model): 27 title = models.CharField(max_length=32)
路由:
1 from django.contrib import admin 2 from django.urls import path, re_path, include 3 4 urlpatterns = [ 5 path(‘admin/‘, admin.site.urls), 6 re_path(‘api/‘, include(‘api.urls‘)), 7 ] 8 9 10 from django.urls import path, re_path, include 11 from api import views 12 13 urlpatterns = [ 14 # 解析 15 re_path(‘(?P<version>[v1|v2]+)/parser/$‘, views.ParserView.as_view()), 16 ]
视图:
1 from django.shortcuts import render, HttpResponse, reverse 2 from rest_framework.views import APIView 3 from rest_framework.parsers import JSONParser, FormParser, MultiPartParser 4 5 6 class ParserView(APIView): 7 # parser_classes = [JSONParser, FormParser, MultiPartParser] 8 """ 9 JSONParser:表示只能解析content-type:application/json头 10 FormParser:表示只能解析content-type:application/x-www-form-urlencoded头 11 MultiPartParser:表示只能解析content-type:multipart/form-data头 12 """ 13 14 def post(self, request, *args, **kwargs): 15 """ 16 可以发json格式数据: 17 a.content-type:application/json b.{"name":"SB","age":18} 18 :param request: 19 :param args: 20 :param kwargs: 21 :return: 22 """ 23 # 获取请求提交的值 24 print(request.data) 25 return HttpResponse(‘ParserView‘)
全局配置:
1 REST_FRAMEWORK = { 2 # 解析 3 ‘DEFAULT_PARSER_CLASSES‘: [‘rest_framework.parsers.JSONParser‘, ‘rest_framework.parsers.FormParser‘], 4 5 }
解析器源码分析
dispatch-->self.get_parsers()-->api_settings.DEFAULT_PARSER_CLASSES
内置解析类
BaseParser def parse(self, stream, media_type=None, parser_context=None):
JSONParser ************* 常用
FormParser ************** 常用
MultiPartParser ******* 文件
FileUploadParser 文件
原文地址:https://www.cnblogs.com/Alexephor/p/11306144.html
时间: 2024-10-06 20:06:01