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 directory
tutorial
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
- upgrade
pip
To 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 installation
Django
As 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 project
tutorial
Notice what follows the command.
, indicates that the current location is the root directory of the projectsettings.py
Put it in the current directory.
C:\code\tutorial
(venv) lambda.django-admin startproject tutorial .
Copy the code
tutorial
Is 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 superuser
admin
The 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 module
tutorial/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 example
HyperlinkedModelSerializer
You can also use primary keys or all sorts of other relationships, but hyperlinks are excellentRESTful
Design.
view
- Open the
tutorial/quickstart/views.py
Writing 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
ViewSet
Class, 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 write
API
的URL
Open,tutorial/urls.py
file
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 automatically
API
generateURL
To configure, you only need to passrouter
Class to register a set of views. - If further control is required
API
的URL
, you can use plain class views and explicitly write routing configuration files. - Finally, we include default login and logout views so that they are browsable
API
(browsable API
). This is optional ifAPI
Authentication is required and you need to use browsableAPI
He will become very useful.
paging
- Paging controls how many objects are returned per page. Can be found in
tutorial/settings.py
Add the following configuration to enable paging.
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination'.'PAGE_SIZE': 10,}Copy the code
Set up the
- in
tutorial/settings.py
Registered inDRF
application
INSTALLED_APPS = [
...
'rest_framework',]Copy the code
Test the API
- open
Django
Built-in development server
C:\code\tutorial
(venv) lambda.python manage.py runserver
Copy the code
- Through the command line tool (
curl
orhttpie
) 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 name
admin
And password123
Then you log in, and then you can manage your users