3、Django获取前端接口传参
我们日常应用中,前端通过接口和后端进行数据交互,后端接收到前端的传参后,根据参数进行对应的逻辑处理,然后返回对应的结果给前端,那么Django框架下,后端是是如何接收前端传入的参数呢?
定义好路由后,我们先简单定义一个视图类,通过接口调用来学习
class Test(View):
def get(self, request):
print('11111')
return JsonResponse({'code': '0', 'message': '查询成功'})
def post(self,request):
print('11111')
return JsonResponse({'code': '0', 'message': '成功'})
一、url路径携带查询字符串传参
例如 http://127.0.0.1:8000/page/test/?name="liang"&age=18
打上断点,发送请求,然后我们通过debug的断点计算器来观察后端接收到的参数

可以看到,request.GET即可获取到前端的此类传参,获取到的类型为QueryDict,我们可以类比为dict类型,通过以下方式可以获取到具体的参数值:
1.request.GET.get("key")

2.request.GET['key']

值得注意的是,如果入参中有两个或多个相同的参数,QueryDict同样可以接收,取一个参数的多个值可以使用request.GET.getlist("key")方法,返回的是一个列表

二、请求体参数
包括:form_data,json格式,xml格式,以及文件上传等
1、form表单
请求如下
我们通过断点来看获取到的数据

request.GET即可获取到前端的此类传参,获取到的类型为QueryDict,我们同样可以类比为dict类型,获取数据方式和上面一样request.POST.get("key"),或者request.POST["key"]
2、json请求体
Content-Type为application/json,name='liang', 'age'=18,我们在代码的对应视图上打上断点后发送请求

这次我们会发现,用request.GET或者request.POST都无法获取到传参,而参数存在于request的body属性中,返回的是基础数据类型---bytes

我们可以通过json.loads(request.body,encoding='utf-8'),将入参转换为常用的dict类型,进行之后的逻辑处理

3.文件上传

解析后的数据同样存储于request的body属性中返回的是基础数据类型---bytes

三、请求头参数
参数存储于request的headers属性中,可以通过request.headers.get('key')来获取

四、路径参数
这种类型的请求,只在url路径中传入的参数,比如传入的一些id值,这些值一般都是动态的,在Django中,这种类型的请求处理方法跟上面几种截然不同,我们一般在路由表中进行正则匹配
路径转换器格式:<url类型转换器:路径参数名>
url类型转换器:int、path、uuid、slug等
urlpatterns = [
path('projects/<int:pk>/',Api_withId.as_view()),
path('projects/',Api.as_view()),
path('test/<int:pk>/',Test.as_view())
]
视图类中实例方法直接增加一个入参,这个入参接受到的既是路径参数,可以在实实例方法中直接调用
class Test(View):
def get(self, request,pk):
print('11111')
return JsonResponse({'code': '0', 'message': '查询成功'})
def post(self,request,pk):
print('11111')
return JsonResponse({'code': '0', 'message': '请求成功'})
