preface
Different frameworks have different design ideas, so they can be used differently. Before starting with the Django REST Framework, there are some basic concepts you must know 🧠 to help you get started with the Django REST Framework.
An 🐧 group is prepared and can be added to 537131912
About The relationship between Django and the Django REST Framework
First of all, the two frameworks were not developed by the same team or organization, of course, as an open source architecture, there must be someone involved in both frameworks. Django was born in 2010, and the Django REST Framework was born in 2011.
Django is the big brother. The Django REST Framework is a subframework that works with Django to develop interfaces. Django can do all the development of a project on its own, but the Django REST Framework does not. It supports a Django supplement that requires Django to work with it.
The first thing to be clear about is that the Django REST Framework can do things, and you can do them with Django. There is nothing Django can’t do if the Django REST Framework can do it.
But using the Django REST Framework can help you accomplish the same tasks with less code. Less code means fewer bugs and less overtime. Not only that, but less code means more code that can be reused and modified later.
Django REST Framework role in backend development
The Django REST Framework is designed to develop apis that you request using HTTP methods and return JSON text.
If you don’t know what an API is, please Google 👍
Returning JSON text does not mean that only JSON text is returned; returning images, videos, and so on is the scope of what the API returns. Returns JSON text in narrow sense, JSON, images, videos, and so on in broad sense
The Django REST Framework doesn’t work by itself. It exists as a subframework of Django. As a general rule, libraries that start with Django should be used with Django, not alone, such as Django-filter.
How do I install and use the Django REST Framework
The installation
Install the Django REST Framework
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
Copy the code
Django REST Framework corresponds to the Python library named DjangorestFramework, which is all lowercase letters with no other delimiters such as Spaces.
In addition to installing the djangorestframework ontology, it is recommended that you install markdown and django-filter. As for what they do ❓, you’ll find out later.
use
I’m just going to introduce you to the two basic concepts, guide packets and guide packets how do you use them
Guide package
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
Copy the code
The syntax for importing packages is from rest_framework import something
Embedded Django
Djangos REST Framework is not used alone. It must be used with Django. You need to add ‘rest_framework’ to the INSTALLED_APPS property in your Django project’s settings.py file. This way, you can enjoy using the Django REST Framework in your Django projects.
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'rest_framework',]Copy the code
About MVT and MVVM architectures
The Django architecture is called MVT, and the Django REST Framework architecture is called MVVM
-
MVT (Model, View, Template)
-
MVVM (Model – View – ViewModel)
The concept itself is meaningless, and for beginners, it is meaningless until you become a god, but here is a brief mention.
On serialization and deserialization
Serialization and deserialization are one of the most important aspects of the Django REST Framework. What is serialization and deserialization ❓ 👇
What is serialization
Serialization is a process like converting a Python object into JSON text. Those of you who know Python know that there are many serialization types in Python, such as lists, tuples, strings, etc., but the serialization here is not to convert XXX things into Python serialization types. Instead, it is to convert these serialization types into JSON text. 🤣
What is deserialization
Deserialization is serializing the other way around. How? Convert JSON text into Python objects
Why introduce serialization into the Django REST Framework
TODO
Serialization and Python objects in serialization are nothing more than dictionaries and lists, as well as numbers and strings contained in dictionaries and lists. Why? Because that’s what the JSON text format looks like.
The relationship and selection between APIView and ViewSet
Django views come in two types: Function Base Views (FBV) and Class Base Views (CBV). FBV is based on a function view, CBV is based on a class view.
The Django REST Framework’s APIView further encapsulates Django’s CBV, and the ViewSet further encapsulates the APIView.
See article TODO for details of what is encapsulated
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, GenericViewSet
Copy the code
Above is the location of the APIView and ViewSet in the REST_framework libraries
As you can see from the name, one is views, which means a bunch of views. A viewset is a bunch of viewsets, what is a viewset? Collection of Views! Aggregation means convergence, so what is convergence? Recall that the ViewSet is a further encapsulation of the APIView, which obviously aggregates a bunch of apiViews together (Python’s multiple inheritance) out of the box. Do you understand? Don’t understand? The simple idea is to turn a single function into a single function through Python’s multiple inheritance.
Instead of using ViewSet directly, we use two subclasses of ViewSet, ModelViewSet and GenericViewSet, whose methods are described below
Speaking of which, what role does Django’s FBV play in the Django REST Framework?
If you don’t even know the concept of view, you are not qualified!! 🤡
Relationship and selection between ModelViewSet and GenericViewSet
TODO
Routing changes using the Django REST Framework
Mapping between ViewSet methods and HTTP methods
The mapping between the two routers is shown in the site-packages\rest_framework\routers.
TIPS: This is only part of the code, but the key stuff is there.
class SimpleRouter(BaseRouter) :
routes = [
# List route.
Route(
url=r'^{prefix}{trailing_slash}$',
mapping={
'get': 'list'.'post': 'create'
},
name='{basename}-list',
detail=False,
initkwargs={'suffix': 'List'}),# Dynamically generated list routes. Generated using
# @action(detail=False) decorator on methods of the viewset.
DynamicRoute(
url=r'^{prefix}/{url_path}{trailing_slash}$',
name='{basename}-{url_name}',
detail=False,
initkwargs={}
),
# Detail route.
Route(
url=r'^{prefix}/{lookup}{trailing_slash}$',
mapping={
'get': 'retrieve'.'put': 'update'.'patch': 'partial_update'.'delete': 'destroy'
},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Instance'}),# Dynamically generated detail routes. Generated using
# @action(detail=True) decorator on methods of the viewset.
DynamicRoute(
url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$',
name='{basename}-{url_name}',
detail=True,
initkwargs={}
),
]
Copy the code
The routes attribute of the SimpleRouter class maps the routes attribute of the SimpleRouter class. The routes attribute of the SimpleRouter class maps the routes attribute of the routes class
The Routes class attribute is a list of Route class instances. The Route class source code is not shown here. The Route of the class
Warning: I mentioned some Python concepts like classes, class instances, class properties, class methods, and so on, This is the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge in the basic knowledge 🤡.
Notice: The following content also involves RESTful specification content, if you do not understand 🤡, hey hey, I do not want to repeat!
Suppose you have a URL: / API /tweets/ and bind this interface with the TweetViewSet view class
The general code is as follows:
It doesn’t matter if you can’t read the code, just read the text description. It doesn’t matter if you can’t read the text description, just read the general idea
The following shows key location codes in the corresponding files, not a panorama
twitter/urls.py
router = routers.SimpleRouter()
router.register(r'api/users', UserViewSet)
router.register(r'api/accounts', AccountViewSet, basename='accounts')
router.register(r'api/tweets', TweetViewSet, basename='tweets')
Copy the code
We use a GET request to access this interface,
Notice: in this case URL/API /tweets/ is an API. Because it has API in its name
Warning: All django-made urls must end with a slash (/). Otherwise, a 302 redirect will be generated, wasting a traffic