django|django rest framework 获取前端参数的几种方式

方式一 常用到GET请求(params)

@url http://example.com/orders?name='shubiao'&color='red'

【django|django rest framework 获取前端参数的几种方式】这种是通过url传参(params),那么应该使用:
from rest_framework.views import APIView from django.http import JsonResponseclass LoginView(APIView): ret = {'code': 1000, 'msg': 'GET'} def get(self, request, *args, **kwargs): name = request.query_params.dict().name # name = 'shubiao' color = request.query_params.dict().color # color = 'red' return JsonResponse(ret)

request.query_params拿到的是QueryDict的类型,使用dict()方法转化为dict
注意:此处可以使用dict()方法,但不要盲目使用dict(), 大家不妨试试{username: ['zhangning', 'ermeng'], age: 18}.dict(), 遇到这种的QueryDict的时候,你可能就会特别特别的开心。一定要试试,一定要试试, 一定要试试!只有试了才能记得住!
方式二 常用到POST请求
1. formdata django|django rest framework 获取前端参数的几种方式
文章图片
image.png
from rest_framework.views import APIView from django.http import JsonResponseclass LoginView(APIView): def post(self, request, *args, **kwargs): ret = {'code': 1000, 'msg': None} usernames = request.data.getlist('username') # usernames = ['zhangning', 'hello'] (list) color = request.data.get('color') # color = 'red' username = request.data.get('username') # username = 'hello' return JsonResponse(ret)

django|django rest framework 获取前端参数的几种方式
文章图片
image.png request.data拿到的参数是QueryDict的类型,此处只讲获取,QueryDict类包含了很多方法,具体的可以参考:https://www.cnblogs.com/scolia/p/5634591.html
2. application/json django|django rest framework 获取前端参数的几种方式
文章图片
image.png
from rest_framework.views import APIView from django.http import JsonResponseclass LoginView(APIView): def post(self, request, slug=None, *args, **kwargs): ret = {'code': 1000, 'msg': None} username = request.data.get('username') # username = 'xiaoming' age= request.data.get('age') # age = 18 (number) languages= request.data.get('languages') # languages = ['js', 'node', 'python'] (list) return JsonResponse(ret)

request.data 拿到是Dict类型
3. application/x-www-form-urlencoded django|django rest framework 获取前端参数的几种方式
文章图片
image.png
from rest_framework.views import APIView from django.http import JsonResponseclass LoginView(APIView): def post(self, request, slug=None, *args, **kwargs): ret = {'code': 1000, 'msg': None} username = request.data.get('username') # username = 'lin' age= request.data.get('age') # age = 18 (number) return JsonResponse(ret)

request.data 拿到的也是QueryDict类型,获取方法可以参考https://www.cnblogs.com/scolia/p/5634591.html链接
注意:
此处都是基于继承 rest framework 中APIView的类重新封装的request来获取参数喔!

    推荐阅读