zoukankan      html  css  js  c++  java
  • rest framework 之路由系统

    一、自定义路由

    1、urls.py

    from django.conf.urls import url, include
    from web.views import s11_render
    
    urlpatterns = [
        url(r'^test/$', s11_render.TestView.as_view()),
        url(r'^test.(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view()),
        url(r'^test/(?P<pk>[^/.]+)/$', s11_render.TestView.as_view()),
        url(r'^test/(?P<pk>[^/.]+).(?P<format>[a-z0-9]+)$', s11_render.TestView.as_view())
    ]
    

    2、views.py

    from rest_framework.views import APIView
    from rest_framework.response import Response
    from .. import models
    
    
    class TestView(APIView):
        def get(self, request, *args, **kwargs):
            print(kwargs)
            print(self.renderer_classes)
            return Response('...')
    

    二、半自动路由

    1、urls.py

    from django.conf.urls import url, include
    from web.views import s10_generic
    
    urlpatterns = [
        url(r'^test/$', s10_generic.UserViewSet.as_view({'get': 'list', 'post': 'create'})),
        url(r'^test/(?P<pk>d+)/$', s10_generic.UserViewSet.as_view(
            {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
    ]
    

    2、views.py

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from rest_framework.viewsets import ModelViewSet
    from rest_framework import serializers
    from .. import models
    
    
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.UserInfo
            fields = "__all__"
    
    
    class UserViewSet(ModelViewSet):
        queryset = models.UserInfo.objects.all()
        serializer_class = UserSerializer
    

    三、全自动路由

    1、urls.py

    from django.conf.urls import url, include
    from rest_framework import routers
    from api.views import TestView, TestView1
    
    
    router = routers.DefaultRouter()
    router.register(r'test1', TestView1)
    
    urlpatterns = [
        url(r'^(?P<version>[v1|v2]+)/', include(router.urls)),
    ]
    

    2、views.py

    from rest_framework.viewsets import ModelViewSet
    from rest_framework import serializers
    from .. import models
    
    
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = models.UserInfo
            fields = "__all__"
    
    class TestView1(ModelViewSet):
        queryset = models.Role.objects.all()
        serializer_class = TestSerializers
        pagination_class = PageNumberPagination
    
  • 相关阅读:
    C++编程开发学习的50条建议(转)
    编程思想:我现在是这样编程的(转)
    Linux系统编程@多线程与多进程GDB调试
    字符串分割函数 STRTOK & STRTOK_R (转)
    C语言指针与数组的定义与声明易错分析
    C语言 a和&a的区别
    C语言二重指针与malloc
    【C语言入门】C语言的组成结构(基础完整篇)!
    程序员吐槽女友败家:开酒店必须400元起步,工资却不到自己的一半!
    怎样才能和编程语言对上眼?你需要做些准备以及...
  • 原文地址:https://www.cnblogs.com/midworld/p/11380180.html
Copyright © 2011-2022 走看看