(瞭解)rest_framework之版本控制, 響應器, url控制器

weixin_33968104發表於2018-12-18

本文均為了解點

版本控制

掌握的:URLPathVersioning

from rest_framework.versioning import URLPathVersioning
-在setting中配置:
REST_FRAMEWORK = {
    'VERSION_PARAM':'version', # url中的key
    'DEFAULT_VERSION':'v1', # 預設版本
    'ALLOWED_VERSIONS': ['v1', 'v2'], # 允許的版本
}


-區域性使用:
​ versioning_class = URLPathVersioning

-全域性使用:

在setting中配置:
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning',
}

路由配置:

url(r'^(?P<version>[v1|v2|v3]+)/books/$', views.Book.as_view({'get':'get_all'}),name='ttt'),    

在檢視類中的request物件中,就可以取出版本號

print(request.version)

反向解析:

url2=request.versioning_scheme.reverse('ttt',request=request)

響應器

rest_framework中用Response返回資料時, 預設返回給瀏覽器的是一個好看的頁面,例如

url為: http://127.0.0.1:8000/book/時, 返回的是頁面

如果不要返回頁面, 而是隻返回資料需要這樣

http://127.0.0.1:8000/book/?format=json

自己指定返回啥

區域性使用:
    首先匯入: 
    from rest_framework.renderers import  JSONRenderer,BrowsableAPIRenderer
    在檢視類中加一行, 想返回什麼裡面放什麼
    renderer_classes = [JSONRenderer, BrowsableAPIRenderer]

全域性使用:
    setting配置:
    REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES':['rest_framework.renderers.JSONRenderer']
}

url控制器

1. 自定義路由(原始方式)

urls.py中:
from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^books/$', views.BookView.as_view()),
    url(r'^books/(?P<pk>\d+)$', views.BookDetailView.as_view()),
]


views.py中
class BookView(APIView):

    def get(self, request):
        book_list = models.Book.objects.all()
        bs = BookSerializers(book_list, many=True)
        return Response(bs.data)

    def post(self, request):
        # 新增一條資料
        print(request.data)

        bs=BookSerializers(data=request.data)
        if bs.is_valid():
            bs.save()  # 生成記錄
            return Response(bs.data)
        else:

            return Response(bs.errors)

class BookDetailView(APIView):
    def get(self,request,pk):
        book_obj=models.Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj,many=False)
        return Response(bs.data)
    def put(self,request,pk):
        book_obj = models.Book.objects.filter(pk=pk).first()

        bs=BookSerializers(data=request.data,instance=book_obj)
        if bs.is_valid():
            bs.save() # update
            return Response(bs.data)
        else:
            return Response(bs.errors)
    def delete(self,request,pk):
        models.Book.objects.filter(pk=pk).delete()

        return Response("")

2. 半自動路由(檢視類必須繼承)

urls.py中
from django.conf.urls import url
from app01 import views
urlpatterns = [
    url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})),
    url(r'^publish/(?P<pk>\d+)/$',
        views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
]


views.py中.
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

3. 全自動路由(自動生成路由)

urls.py中
from django.conf.urls import url,include
from app01 import views
from rest_framework import routers
router=routers.DefaultRouter()
# 兩個引數,一個是匹配的路由,一個是檢視中寫的CBV的類
router.register('publish',views.PublishView)
urlpatterns = [
    # http://127.0.0.1:8000/publish/format=json(渲染器通過這個判斷,返回渲染的頁面)
    # url(r'^publish/', views.PublishView.as_view({'get':'list','post':'create'})),
    # http://127.0.0.1:8000/publish.json(渲染器通過這個判斷,返回渲染的頁面)
    # url(r'^publish\.(?P<format>\w+)$', views.PublishView.as_view({'get':'list','post':'create'})),
    
    # 可以用 以下方式訪問
    # 1 http://127.0.0.1:8000/publish/
    # 2 http://127.0.0.1:8000/publish.json
    # 3 http://127.0.0.1:8000/publish/3
    # 4 http://127.0.0.1:8000/publish/3.json   
    url(r'',include(router.urls))
]



views.py中.
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
    queryset=models.Publish.objects.all()
    serializer_class=PublishSerializers

相關文章