Django-Rest frameworw之解析器

一、解析器

        根据请求头 content-type 选择对应的解析器就请求体内容进行处理。

        注意:个别特殊的值可以通过Django的request对象 request._request 来进行获取


media_type = None # application/json  application/x-www-form-urlencoded  multipart/form-data等 #根据这个匹配使用哪个解析器

def parse(self, stream, media_type=None, parser_context=None): #关键方法
pass

二、解析器示例

==============******==============

            1、仅处理请求头content-type为application/json的请求体

            2、仅处理请求头content-type为application/x-www-form-urlencoded 的请求体

            3、仅处理请求头content-type为multipart/form-data的请求体

            4、 仅上传文件

            5、 同时多个Parser

==============******==============

全局使用

in settings.py  #直接copy REST_FRAMEWORK到配置文件就行
	REST_FRAMEWORK = {
	    'DEFAULT_PARSER_CLASSES':[
	        'rest_framework.parsers.JSONParser' #使用的解析器
	        'rest_framework.parsers.FormParser'
	        'rest_framework.parsers.MultiPartParser'
	    ]

	}


1、仅处理请求头content-type为application/json的请求体

in urls.py
	from django.conf.urls import url, include
	from web.views.s5_parser import TestView

	urlpatterns = [
	    url(r'test/', TestView.as_view(), name='test'),
	]
in views.py
	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from rest_framework.request import Request
	from rest_framework.parsers import JSONParser


	class TestView(APIView):
	    parser_classes = [JSONParser, ]

	    def post(self, request, *args, **kwargs):
	        print(request.content_type)

	        # 获取请求的值,并使用对应的JSONParser进行处理
	        print(request.data)

	        # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
	        print(request.POST)
	        print(request.FILES)

	        return Response('POST请求,响应内容')

	    def put(self, request, *args, **kwargs):
	        return Response('PUT请求,响应内容')


2、仅处理请求头content-type为application/x-www-form-urlencoded 的请求体

in urls.py
	from django.conf.urls import url, include
	from web.views import TestView

	urlpatterns = [
	    url(r'test/', TestView.as_view(), name='test'),
	]
in views.py
	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from rest_framework.request import Request
	from rest_framework.parsers import FormParser


	class TestView(APIView):
	    parser_classes = [FormParser, ]

	    def post(self, request, *args, **kwargs):
	        print(request.content_type)

	        # 获取请求的值,并使用对应的JSONParser进行处理
	        print(request.data)

	        # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
	        print(request.POST)
	        print(request.FILES)

	        return Response('POST请求,响应内容')

	    def put(self, request, *args, **kwargs):
	        return Response('PUT请求,响应内容')

3、仅处理请求头content-type为multipart/form-data的请求体

in urls.py
	from django.conf.urls import url, include
	from web.views import TestView

	urlpatterns = [
	    url(r'test/', TestView.as_view(), name='test'),
	]

in views.py
	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from rest_framework.request import Request
	from rest_framework.parsers import MultiPartParser


	class TestView(APIView):
	    parser_classes = [MultiPartParser, ]

	    def post(self, request, *args, **kwargs):
	        print(request.content_type)

	        # 获取请求的值,并使用对应的JSONParser进行处理
	        print(request.data)
	        # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
	        print(request.POST) 
	        print(request.FILES)
	        return Response('POST请求,响应内容')

	    def put(self, request, *args, **kwargs):
	        return Response('PUT请求,响应内容')

in  upload.html
		<!DOCTYPE html>
		<html lang="en">
		<head>
		    <meta charset="UTF-8">
		    <title>Title</title>
		</head>
		<body>
		<form action="http://127.0.0.1:8000/test/" method="post" enctype="multipart/form-data">
		    <input type="text" name="user" />
		    <input type="file" name="img">

		    <input type="submit" value="提交">
                </form>
		</body>
		</html>

4、 仅上传文件

in urls.py
	from django.conf.urls import url, include
	from web.views import TestView

	urlpatterns = [
	    url(r'test/(?P<filename>[^/]+)', TestView.as_view(), name='test'),
	]
in views.py
	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from rest_framework.request import Request
	from rest_framework.parsers import FileUploadParser


	class TestView(APIView):
	    parser_classes = [FileUploadParser, ]

	    def post(self, request, filename, *args, **kwargs):
	        print(filename) 
	        print(request.content_type)

	        # 获取请求的值,并使用对应的JSONParser进行处理
	        print(request.data)
	        # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
	        print(request.POST) # 没有内容
	        print(request.FILES) # 有内容
	        return Response('POST请求,响应内容')

	    def put(self, request, *args, **kwargs):
	        return Response('PUT请求,响应内容')
in upload.html
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>Title</title>
	</head>
	<body>
	<form action="http://127.0.0.1:8000/test/f1.numbers" method="post" enctype="multipart/form-data">
	    <input type="text" name="user" />
	    <input type="file" name="img">

	    <input type="submit" value="提交">

	</form>
	</body>
	</html>

5、 同时多个Parser

        当同时使用多个parser时,rest framework会根据请求头content-type自动进行比对,并使用对应parser

in urls.py
	from django.conf.urls import url, include
	from web.views import TestView

	urlpatterns = [
	    url(r'test/', TestView.as_view(), name='test'),
	]
in views.py
	#!/usr/bin/env python
	# -*- coding:utf-8 -*-
	from rest_framework.views import APIView
	from rest_framework.response import Response
	from rest_framework.request import Request
	from rest_framework.parsers import JSONParser, FormParser, MultiPartParser


	class TestView(APIView):
	    parser_classes = [JSONParser, FormParser, MultiPartParser, ]

	    def post(self, request, *args, **kwargs):
	        print(request.content_type)

	        # 获取请求的值,并使用对应的JSONParser进行处理
	        print(request.data)
	        # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
	        print(request.POST)
	        print(request.FILES)
	        return Response('POST请求,响应内容')

	    def put(self, request, *args, **kwargs):
	        return Response('PUT请求,响应内容')


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页