django 路由
1.SimpleRouter
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register(r'users', UserViewSet)
register有两个强制参数
prefix 此组路由的url前缀
viewset 处理请求的viewset类
还有一个可选参数
base_name 如果视图集不包括queryset属性,那么在注册视图集时必须设置base_name也就是viewset 没有自定义model 或 get_queryset方法时,必须填写此属性
生成的路由
URL pattern: ^users/$ Name: 'user-list'
URL pattern: ^users/{pk}/$ Name: 'user-detail'
在路由中的使用
方法一:
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
]
urlpatterns += router.urls
方法二:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^', include(router.urls)),
]
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
]
额外连接和操作
用@detail_route或@list_route装饰的视图集上的任何方法也将被路由
class TestViewSet(viewsets.ViewSet):
permission_classes = []
from rest_framework.decorators import detail_route, list_route
@detail_route(methods=['GET'])
def url_test(self, request, pk=None, *args, **kwargs):
return Response(pk)
生成的路由 ^/test/(?P<pk>[^/.]+)/url_test/$
如果要自定义路由名,使用url_path参数定义
@detail_route(methods=['get'], url_path='zb')
# 自定义组名和正则
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_id'
lookup_value_regex = '[0-9a-f]{32}'
1.ExtendedDefaultRouter
from rest_framework_extensions.routers import ExtendedDefaultRouter
router.register(r'/we_chat', WeChatPayViewSet, 'we_chat')
class WeChatPayViewSet(viewsets.ViewSet):
permission_classes = (IsAuthenticated,)
@action(methods=["POST"], is_for_list=True)
def app_pay(self, request, *args, **kwargs):
‘’‘
当viewset使用@action时
class TestViewSet(viewsets.ViewSet):
model = EStoreOrder
@action(methods=['GET'])
def test(self, request, *args, **kwargs):
return Response('ok')
生成的路由为
^api/ ^estore ^/test/(?P<pk>[^/.]+)/test/$ [name='estoreorder-test']
^api/ ^estore ^/test/(?P<pk>[^/.]+)/test/.(?P<format>[a-z0-9]+)$ [name='estoreorder-test']
当使用
@action(methods=['GET'], is_for_list=True)
生成的路由为
^api/ ^estore ^/test/test/$ [name='estoreorder-test-list']
^api/ ^estore ^/test/test/.(?P<format>[a-z0-9]+)$ [name='estoreorder-test-list']
’‘’