This is the 20th day of my participation in the August More Text Challenge

DRF is quick to learn

This tutorial will create a simple API that allows administrators to view and edit users and groups in the system.


Project configuration

  • Create a project directorytutorial
C:\code  
λ mkdir tutorial

C: \code  
λ cd tutorial
Copy the code
  • Generate and activate the virtual environment
C:\code\tutorial  
λ python -m venv venv

C: \code\tutorial  
λ cd venv/scripts

C: \code\tutorial\venv\Scripts  
λ activate
Copy the code
  • upgradepipTo the latest version (20.2.4)
C:\code\tutorial  
(venv) lambda.python -m pip install -U pip.Successfully installed pip- 20.2.4Copy the code
  • The installationDjangoAs well asDRF
C:\code\tutorial  
(venv) lambda.pip install django.Successfully installed asgiref- 3.2.10django- 3.1.2pytz2020.1sqlparse- 0.4.1C: \code\tutorial  
(venv) lambda.pip install djangorestframework.Successfully installed djangorestframework- 3.12.1Copy the code
  • Create a projecttutorialNotice what follows the command., indicates that the current location is the root directory of the projectsettings.pyPut it in the current directory.
C:\code\tutorial  
(venv) lambda.django-admin startproject tutorial .
Copy the code
  • tutorialIs aSingle application projectTo create an applicationquickstart
C:\code\tutorial  
(venv) lambda.cd tutorial

C: \code\tutorial\tutorial  
(venv) lambda.django-admin startapp quickstart

C: \code\tutorial\tutorial  
(venv) lambda.cd.C: \code\tutorial  
(venv) lambda.Copy the code
  • The final project structure is as follows

  • The quickStart application is placed in the Tutorial project folder, which may seem odd, but doing so takes advantage of the project’s namespace to avoid naming conflicts with external modules.

Note: If there is an external module called QuickStart, the traditional project structure will cause conflicts when importing the QuickStart application. However, when the application is placed in the project Settings folder, tutorial.quickstart. XXX is written when importing. In this case, the project folder forms a package namespace, reducing the possibility of naming conflicts.

  • Perform the migration to synchronize the database
C:\code\tutorial  
(venv) lambda.python manage.py migrate
Copy the code
  • Create a superuseradminThe password for123
C:\code\tutorial  
(venv) lambda.python manage.py createsuperuser --username admin --email admin@example.com
Copy the code

The serializer

  • Start by defining some serializers and creating a new moduletutorial/quickstart/serializers.py, which will be used to render data.
from django.contrib.auth.models import Group, User
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer) :
    class Meta:
        model = User
        fields = ['url'.'username'.'email'.'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer) :
    class Meta:
        model = Group
        fields = ['url'.'name']
Copy the code
  • Used in this exampleHyperlinkedModelSerializerYou can also use primary keys or all sorts of other relationships, but hyperlinks are excellentRESTfulDesign.

view

  • Open thetutorial/quickstart/views.pyWriting views
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer


class UserViewSet(viewsets.ModelViewSet) :
    "" allows viewing and editing of the user's API endpoint. "" "
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet) :
    "" allows viewing and editing of API endpoints for groups. "" "
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]
Copy the code
  • This is where all the common operations are integrated into one calledView the set ViewSetClass, rather than writing multiple views separately.
  • You can split a view set into separate views if you need to, but a view set organizes the view logic well and is very concise.

routing

  • Begin to writeAPIURLOpen,tutorial/urls.pyfile
from django.urls import include, path
from rest_framework import routers

from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Use the automatic routing connection API
In addition, the LOGIN route is included for the browsable API
urlpatterns = [
    path(' ', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),]Copy the code
  • Because we are using a view set instead of a view, we can automaticallyAPIgenerateURLTo configure, you only need to passrouterClass to register a set of views.
  • If further control is requiredAPIURL, you can use plain class views and explicitly write routing configuration files.
  • Finally, we include default login and logout views so that they are browsableAPI(browsable API). This is optional ifAPIAuthentication is required and you need to use browsableAPIHe will become very useful.

paging

  • Paging controls how many objects are returned per page. Can be found intutorial/settings.pyAdd the following configuration to enable paging.
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'.'PAGE_SIZE': 10,}Copy the code

Set up the

  • intutorial/settings.pyRegistered inDRFapplication
INSTALLED_APPS = [
    ...
    'rest_framework',]Copy the code

Test the API

  • openDjangoBuilt-in development server
C:\code\tutorial  
(venv) lambda.python manage.py runserver
Copy the code
  • Through the command line tool (curlorhttpie) to access the interface, or directly using a browserhttp://127.0.0.1:8000/users/
  • Click on the upper right corner and enter a user nameadminAnd password123Then you log in, and then you can manage your users