文章目录
- 路由
- 解析器
- 1.JSONParser
- 2.FormParser
- 3.MultiPartParser
- 4.FileUploadParser
路由
在之前进行drf开发时,对于路由我们一般进行两种配置:
-
视图继承APIView
from django.urls import path from app01 import views urlpatterns = [ path('api/users/', views.UserView.as_view()), ]
-
视图继承
ViewSetMixin
(GenericViewSet、ModelViewSet)from django.urls import path, re_path, include from app01 import views urlpatterns = [ path('api/users/', views.UserView.as_view({"get":"list","post":"create"})), path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})), ]
对于这种形式的路由,drf中提供了更简便的方式:
可以使用rest_framework中的router来简化视图函数继承GenericViewSet或者ModelViewSet是的路由分发
from rest_framework import routers from app01 import views router = routers.SimpleRouter() router.register(r'api/users', views.UserView) urlpatterns = [ # 其他URL # path('xxxx/', xxxx.as_view()), ] urlpatterns += router.urls
也可以利用include,给URL加前缀:
from django.urls import path, include from rest_framework import routers from app01 import views router = routers.SimpleRouter() router.register(r'users', views.UserView) urlpatterns = [ path('api/', include((router.urls, 'app_name'), namespace='instance_name')), # 其他URL # path('forgot-password/', ForgotPasswordFormView.as_view()), ]
解析器
之前使用 request.data
获取请求体中的数据。
这个 reqeust.data
的数据怎么来的呢?其实在drf内部是由解析器,根据请求者传入的数据格式 + 请求头来进行处理。
1.JSONParser
2.FormParser
3.MultiPartParser
<!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.FileUploadParser
解析器可以设置多个:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, JSONParser, FormParser
class UserView(APIView):
def post(self, request):
print(request.content_type)
print(request.data)
return Response("...")
drf默认使用3个解析器:
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
若有错误与不足请指出,关注DPT一起进步吧!!!