• 【DRF框架】路由组件


    视图组件涉及的路由补充:

      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(r'book_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']

     

  • 相关阅读:
    【BZOJ 4631】4631: 踩气球 (线段树)
    【BZOJ 4148】 4148: [AMPPZ2014]Pillars (乱搞)
    【LYOI 212】「雅礼集训 2017 Day8」价(二分匹配+最大权闭合子图)
    【BZOJ 4104】 4104: [Thu Summer Camp 2015]解密运算 (智商)
    【BZOJ 4103】 4103: [Thu Summer Camp 2015]异或运算 (可持久化Trie)
    【BZOJ 3747】 3747: [POI2015]Kinoman (线段树)
    【BZOJ 3997】 3997: [TJOI2015]组合数学 (DP| 最小链覆盖=最大点独立集)
    【BZOJ 3727】 3727: PA2014 Final Zadanie (递推)
    【BZOJ 3442】 3442: 学习小组 (最大费用流)
    【BZOJ 3218】 3218: a + b Problem(最小割+可持久化线段树)
  • 原文地址:https://www.cnblogs.com/st-st/p/10124465.html
Copyright © 2020-2023  润新知