路由组件
基本使用
1.ViewSetMixin 介绍
特点,只要继承它,路由写法变了
eg:
path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
ViewSetMixin 源码分析
""" 如果请求来了,会执行 view(request)"""
class ViewSetMixin:
@classonlymethod
def as_view(cls, actions=None, **initkwargs):
# actions={'get': 'list', 'post': 'create'}
def view(request, *args, **kwargs):
# method:get action:list
for method, action in actions.items():
# handler就是list
handler = getattr(self, action) #视图类反射有没有list
# 反射:把get变成了list
setattr(self, method, handler)
return self.dispatch(request, *args, **kwargs)
return csrf_exempt(view)
2.代码展示
(1)模型层
"""必须先继承 ViewSetMixin, 后继承 APIView """
from rest_framework.views import APIView # 导入
from rest_framework.viewsets import ViewSetMixin # 导入
from rest_framework.decorators import action # 装饰器 action 导入
class PublishView(ViewSetMixin, APIView):
""" 方式一: """
# detail=False 路由中不带pk
# url_path :如果不写,就是函数名生成的路径 ==> http://127.0.0.1/publish/lqzqqq
# 如果写了 ==> ==> http://127.0.0.1/publish/lqz
# 浏览器映射为===> ^publish/lqz/$ [name='publish-lqz'] === http://127.0.0.1/publish/lqz
# url_path 做反向解析,一般不用写。
@action(methods=['POST', 'GET'], detail=False, url_path='lqz', url_name='lqz')
def lqzqqq(self, request):
return Response('lqz')
"""方式二: """
# detail=True 方法中的PK必须传
# 浏览器映射为===> ^publish/(?P<pk>[^/.]+)/lqz/$ [name='publish-lqz'] === http://127.0.0.1/publish/pk/lqz === http://127.0.0.1/publish/5/lqz
@action(methods=['POST', 'GET'], detail=True, url_path='lqz', url_name='lqz')
def lqzqqq(self, request, pk):
print(pk)
return Response('lqz')
def login(self, request):
return Response('login')
2.路由层
from rest_framework.routers import SimpleRouter, DefaultRouter
# 也可以 DefaultRouter() 实例化,两者大差不差。
router = SimpleRouter()
router.register('books', views.BookView, 'books')
router.register('publish', views.PublishView, 'publish')
urlpatterns = [
]
""" 访问路由 """
http://127.0.0.1/publish/lqz
(1) 路由注册
方式一:
# 在最下面注册
urlpatterns+=router.urls
方式二:
# 在最下面注册
urlpatterns = [
# ''中无需写字段(也可以写)。
path('', include(router.urls)),
]