1. 程式人生 > >【DRF框架】路由組件

【DRF框架】路由組件

crete try cti bsp work perf csr his example

視圖組件涉及的路由補充:

  from rest_framework.viewsets import ViewSetMixin

  對路由進行了重新的分發,重寫了as_view() 方法,重新封裝了請求方法

from rest_framework.viewsets import ViewSetMixin

class ViewSetMixin(object):
    """
    This is the magic.

    Overrides `.as_view()` so that it takes an `actions` keyword that performs
    the binding of HTTP methods to actions on the Resource.

    For example, to create a concrete view binding the ‘GET‘ and ‘POST‘ methods
    to the ‘list‘ and ‘create‘ actions...

    view = MyViewSet.as_view({‘get‘: ‘list‘, ‘post‘: ‘create‘})
    
""" @classonlymethod def as_view(cls, actions=None, **initkwargs): # actions就是傳入的字典 def view(request, *args, **kwargs): self = cls(**initkwargs) self.action_map = actions # 循環字典{"get":"list"} for method, action in actions.items():
# self是定義的視圖類 handler = getattr(self, action) # 將self.get 改為 self.list setattr(self, method, handler) if hasattr(self, get) and not hasattr(self, head): self.head = self.get self.request = request self.args
= args self.kwargs = kwargs # 重新執行分發 return self.dispatch(request, *args, **kwargs) return csrf_exempt(view) # APIView def dispatch(self, request, *args, **kwargs): try: self.initial(request, *args, **kwargs) # 重新封裝分發 # self.get已經是self.list if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response

路由組件

from rest_framework.routers import DefaultRouter

# urls.py
from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from .view4 import BookView

# 實例化路由對象
router = DefaultRouter()

# 註冊路由和視圖
router.register(rbook_list,BookView)

urlpatterns = [

]

# 添加到路由列表中
urlpatterns += router.urls

自動生成的路由

默認生成的路由都是帶參數的!

^admin/
^api/book/ ^book_list/$ [name=book-list]
^api/book/ ^book_list\.(?P<format>[a-z0-9]+)/?$ [name=book-list]
^api/book/ ^book_list/(?P<pk>[^/.]+)/$ [name=book-detail]
^api/book/ ^book_list/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name=book-detail]
^api/book/ ^$ [name=api-root]
^api/book/ ^\.(?P<format>[a-z0-9]+)/?$ [name=api-root]

【DRF框架】路由組件