标签:执行 请求 detail des router setattr route 列表 bsp
视图组件涉及的路由补充:
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‘]
标签:执行 请求 detail des router setattr route 列表 bsp
原文地址:https://www.cnblogs.com/st-st/p/10124465.html