rest_framework-09-路由

 

rest_framework-09-路由

路由

 1.最原始的路由

 

2.?问号传参 等于号=    渲染器json格式,  http://127.0.0.1:8080/api/v1/view1/1/?format=json

运行结果:

 

 

 3. .json 点后面可以写字母、数字等等   http://127.0.0.1:8080/api/v1/view1.json

 

运行结果:

#4.  数字.json   http://127.0.0.1:8080/api/v1/view1/1/ 或者 http://127.0.0.1:8080/api/v1/view1/1.json/

 

 

 

运行结果:http://127.0.0.1:8080/api/v1/view1/1.json/

 

 

代码:

 urls.py

    # 2. 渲染器,等于号=json格式  http://127.0.0.1:8080/api/v1/view1/1/?format=json
    url(r'^(?P<version>[v1|v2]+)/view1/$', views.View1View.as_view({'get': 'list','post':'create'})),

    # 3..json 点后面可以写字母、数字等等  http://127.0.0.1:8080/api/v1/view1.json/
    url(r'^(?P<version>[v1|v2]+)/view1\.(?P<format>\w+)$', views.View1View.as_view({'get': 'list','post':'create'})),

    # 4. http://127.0.0.1:8080/api/v1/view1/1/ 或者  http://127.0.0.1:8080/api/v1/view1/1.json/
    url(r'^(?P<version>[v1|v2]+)/view1/(?P<pk>\d+)/$', views.View1View.as_view({
        'get': 'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
    url(r'^(?P<version>[v1|v2]+)/view1/(?P<pk>\d+)\.(?P<format>\w+)/$', views.View1View.as_view({
        'get': 'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),

 

views.py

#===================================================================ModelViewSet  # 视图

from api.utils.serializers.pager import PagerSerializers  # 序列化
from rest_framework.response import Response # 渲染器
from rest_framework.pagination import PageNumberPagination # 分页
from rest_framework.viewsets import GenericViewSet, ModelViewSet  # 视图
from rest_framework.mixins import ListModelMixin,CreateModelMixin  # 可继承(增删改查)

# class View1View(ListModelMixin,CreateModelMixin,GenericViewSet):
class View1View(ModelViewSet):

    queryset = models.Role.objects.all()  # 所有数据集合
    serializer_class = PagerSerializers  # 序列化对象
    pagination_class = PageNumberPagination # 分页对象

 

 自动路由

1.urls.py

url带版本

views.py还没改变。

 

运行错误的url结果:

 运行正确的url结果:http://127.0.0.1:8080/api/v1/rt/  查看所有数据

  运行正确的url结果:http://127.0.0.1:8080/api/v1/rt.json/  查看所有数据 json格式

 

 

 

urls.py代码:

from django.conf.urls import url,include
from api import views

# 自动生成路由
from rest_framework import routers
# 路由前缀
router = routers.DefaultRouter()
router.register(r'xxx', views.View1View) # 默认会生成4个url,前缀xxx
router.register(r'rt', views.View1View) # 默认会生成4个url,前缀rt
urls.py
# 自定义路由
url(r'^',include(router.urls)),
 

views.py代码:

#===================================================================ModelViewSet  # 视图

from api.utils.serializers.pager import PagerSerializers  # 序列化
from rest_framework.pagination import PageNumberPagination # 分页
from rest_framework.viewsets import GenericViewSet, ModelViewSet  # 视图

class View1View(ModelViewSet): queryset = models.Role.objects.all() # 所有数据集合 serializer_class = PagerSerializers # 序列化对象 pagination_class = PageNumberPagination # 分页对象

 

 
 
posted @ 2018-07-08 19:02  yimi+fly  阅读(178)  评论(0编辑  收藏  举报