程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django API development: View setting and routing

編輯:Python

Preface

View set and Router yes Django REST Framework Tools in , Can speed up API Development . They are views and URL An additional layer of abstraction above . The main benefit is that a single view set can replace multiple related views . Routers can automatically generate for developers URL. In large projects with many endpoints , This means that developers have to write less code . so to speak , With a long list of single views and URL comparison , For experienced developers , Compared with a small number of view sets and router combinations , It is easier to understand and reason .


In this chapter , We will add two new... To the existing project API Endpoint , And learn how to view and URL Switching to view sets and routers can achieve the same functionality with less code .

user terminal

At present , Our project has the following API Endpoint . They all use api/v1/ start , For brevity , They are not shown :




The first two endpoints are created by us , and django-rest-auth Five more endpoints are provided . Now let's add two other endpoints , To list all users and individual users . This is a lot of API Common functions in , It will give us a clearer understanding of why our views and URL Refactoring into view sets and routers makes sense .


Tradition Django With built-in User Model class , We have used this class for authentication in the last article . therefore , We do not need to create a new database model . contrary , We just need to connect the new endpoint . This process always involves the following three steps :


  • New model serializer

  • Add each endpoint view

  • Add... For each endpoint URL route


Start with our serializer . We need to import User Model , Then create a... That uses it UserSerializer class . Then add it to our existing posts/serializers.py In file .


# posts/serializers.pyfrom django.contrib.auth import get_user_model # new from rest_framework import serializersfrom .models import Postclass PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'author', 'title', 'body', 'created_at',)class UserSerializer(serializers.ModelSerializer): # new class Meta: model = get_user_model() fields = ('id', 'username',)


It is worth noting that , Although we use here get_user_model To quote User Model , But it's actually Django There is 3 Different ways To quote User Model .


By using get_user_model , We ensure that we are referencing the correct user model , Whether it's the default user model or the new one Django Often defined in projects Custom user model .


Next , We need to define views for each endpoint . First of all, will UserSerializer Add to import list . Then create a list of all users UserList Class and... That provide a detailed view of a single user UserDetail class . Just like our post view , We can use... Here ListCreateAPIView and RetrieveUpdateDestroyAPIView.


For each endpoint , We just need to read only or GET function . This means that we can use ListAPIView and RetrieveUpdateDestroyAPIView . We still need to pass get_user_model Reference user model , To import it into the first line .


# posts/views.pyfrom django.contrib.auth import get_user_model # new from rest_framework import genericsfrom .models import Postfrom .permissions import IsAuthorOrReadOnlyfrom .serializers import PostSerializer, UserSerializer # newclass PostList(generics.ListCreateAPIView): 0 queryset = Post.objects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer class UserList(generics.ListCreateAPIView): # new queryset = get_user_model().objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveUpdateDestroyAPIView): # new queryset = get_user_model().objects.all() serializer_class = UserSerializer


If you notice , There are many repetitions here . Post The view and User Views have exactly the same queryset and serializer_class.

Last , We have it. URL route . Make sure to import the new UserList and UserDetail View . then , We can use prefixes for each user users/.


# posts/urls.pyfrom django.urls import pathfrom .views import UserList, UserDetail, PostList, PostDetail # newurlpatterns = [ path('users/', UserList.as_view()), # new path('users/<int:pk>/', UserDetail.as_view()), # new path('', PostList.as_view()), path('<int:pk>/', PostDetail.as_view()),]


We finished . Make sure the local server is still running , And jump to the browsable API To make sure everything is OK .


Our user list endpoint is located at http://127.0.0.1:8000/api/v1/users/




Status code is 200 OK , It means that everything is normal . We can see three existing users .


There is a user details endpoint on the primary key of each user . therefore , Our super user account is located at :http://127.0.0.1:8000/api/v1/users/1/.



View set

A view set is a way to logically combine multiple related views into a single class . let me put it another way , A view set can replace multiple views . At present , We have four views : Two for blog posts , Two for users . contrary , We can use two view sets to mimic the same functionality : One for blog posts , The other is for users .


The compromise is , For other developers who are not very familiar with view sets , Readability will decrease . So this is a trade-off . When we swap view sets , The code is updated posts/views.py This is what the document says .


# posts/views.pyfrom django.contrib.auth import get_user_model from rest_framework import viewsets # newfrom .models import Postfrom .permissions import IsAuthorOrReadOnlyfrom .serializers import PostSerializer, UserSerializerclass PostViewSet(viewsets.ModelViewSet): # new permission_classes = (IsAuthorOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer class UserViewSet(viewsets.ModelViewSet): # new queryset = get_user_model().objects.all() serializer_class = UserSerializer


At the top , Not from rest_framework Import generics , We now import the view set on the second line . then , We use ModelViewSet, It provides us with a list view and a detail view . and , We no longer need to repeat the same for each view as before queryset and serializer_class .

Routers route

Use directly with view sets , To automatically generate URL Pattern . Our current posts/urls.py The file has four URL Pattern : Two for blog posts , Two for users . contrary , We can take a route for each view set . therefore , Use two routes instead of four URL Pattern . Sounds better ?


Django REST Framework There are two default routers :SimpleRouter and DefaultRouter . We will use SimpleRouter, But you can also create custom routers for more advanced features .


The updated code looks like this :


# posts/urls.pyfrom django.urls import pathfrom rest_framework.routers import SimpleRouterfrom .views import UserViewSet, PostViewSetrouter = SimpleRouter()router.register('users', UserViewSet, base_name='users') router.register('', PostViewSet, base_name='posts')urlpatterns = router.urls


On the top line , Will import SimpleRouter And its view . The router is set to SimpleRouter, We provide users and posts “ register ” Each view set . Last , We will URL Set to use the new router .


Continue and immediately check our four endpoints ! The list of users is the same .




however , The detail view is somewhat different . Now it is called “ User instance ”, instead of “ User details ”, And there is an additional “ Delete ” Options are built into ModelViewSet in .




You can customize the view set , But an important tradeoff is writing less code with the view set , This is the default setting , It may require some additional configuration to match exactly what you want .


Go to the release list , We can see that it is the same :




It is important to , Our permissions are still valid . Use our testuser2 When the account is logged in ,Post Instance As read-only .




however , If we use a superuser account ( This log is the author of a separate blog post ) Logon , Then we will have complete reading and writing - edit - Delete permission .



summary

View sets and routers are a powerful abstraction , It can reduce the amount of code that developers have to write . however , This simplicity comes at the expense of the initial learning curve . The first few uses view sets and routers instead of views and URL Patterns can feel strange .


Final , The decision when to add view sets and routers to a project is quite subjective . A good rule of thumb is from the view and URL Start . With API The increase in complexity , If you find yourself repeating the same endpoint pattern over and over again , Then check the view set and the router .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved