Django REST framework basic use

DRF

Python-based build, to achieve a heavyweight framework RESTApi style, in Django basis, plus many implementations, customized richer functionality, has great customizable.

Official website: https://www.django-rest-framework.org/

Chinese document: https://q1mi.github.io/Django-REST-framework-documentation/

  • characteristic
    • Browse API
    • Provide rich Certification
    • Support data serialization
      • dict turn json, json turn dict
    • It can be embedded in a lightweight, only the model FBV
    • Strong community support

init your brain

Installation

pip install djangorestframework

Sign in INSTALLED_APPS project settings.py in:'rest_framework'

Project Directory

The main difference is and Django

In the app

  1. serializers.py

Serializers.py create your own file, in which the class is used to create a data model ModelnameSerializer sequence (serializers.ModelSerializer), which defines the metaclass Meta used to develop the model name, and return the data

class GameSerializer(serializers.Modelserializer):
	class Meta:
		model = Game
		fields = ("id", "g_name", "g_price")

Can also be inherited from (serializers.Serializer), you need to implement an abstract method create (), update () method (must be rewritten), the basic format for the next, but generally do not use.

class GameSerializer(serializers.Serializer):
	id = serializers.IntegerField(read_only=True)
	g_name = serializers.CharField(max_length=32)
	g_price = serializers.FloatField(default=11)
	
	# 重写方法,传入一个经过确认的数据,字典,在Serializer中有一个将数据格式化为字典的方法
	def create(self, validated_data)return Game.objects.create(**validated_data)
	
	def update(self, instance, validated_data):
		instance.g_name = validated_data.get("g_name", instance.g_name)
		instance.g_price = validated_data.get("g_price") or instance.g_price
		instance.save()
		return instance
  1. views.py use class

Define a NameViewSet (viewsets.ModelViewSet) class, automatically creates a tuple of view, it contains a series of views.

Properties must be defined:

class BookViewSet(viewsets.ModelViewSet):
	queryset = Book.objects.all()
	serializer_class = BookSerializer

In the multistage parent class GenericAPIView, the default queryset = None, serializer_class = None, but will get the two parameters in the process of its class, is not given to these two parameters defining NameViewSet.

  1. The app urls.py

Use router and NameViewSet created above () to register the route, at the root of the project route can be used to register the router can also be used to register appname

Registration urls.py route:

router = routers.DefaultRouter()
# 路由全称为'/app/books/',BookViewSet为views.py中创建的路由类
router.register(r'books', views.BookViewSet)

Root routing

App urls registered with the routing:

from app.urls import router
# 使用app的urls里定义的router来注册路由
url(r'app/', include(router.urls)),
# 使用appname来注册路由
url(r'ser/', include("LearnSerializer.urls"))

Start the test

  • He realized the direct CRUD data returned in the browser page has been written
  • Can be directly accessed directly at the page returned
  • You can use the API form, json format display

Serialization serializers

Implemented in three ways serialization inherited from three different serializers classes, different wording.

  1. serializsers.Serializer
  2. serializers.ModelSerializer
  3. serializers.HyperLinkedModelSerializer

General development longest use serializers.ModelSerializer, writing most convenient

characteristic:

serializers.Serializer:

  • Feature
    • Manually writing field
    • Must implement the abstract methods: create and update
  • Use serializer
    • model into json
    • json into a model

model into JSON, in accordance with the object model as a template to construct a sequence of objects, if an odd number may be passed directly, if plural, to add many = True

class GamesView(View):

    def get(self, request):
        games = Game.objects.all()
        # 返回的是多个对象,需要添加many=True
        serializer = GameSerializer(games, many=True, context={'request': request})
        return JsonResponse(serializer.data, safe=False)
model
dict
json

json into model, using the data fetch dict serialized objects ConstructionxxxSerializer(data=dict)

First is_valid verification, then call save method, the authentication fails, the call errors () properties

class GamesView(View):
    def post(self, request):
        g_name = request.POST.get("g_name")
        g_price = request.POST.get("g_price")
        source_data = {
            "g_name": g_name,
            "g_price": g_price
        }
        serializer = GameSerializer(data=source_data)
        # 验证数据
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors)
json
dict
model

serializers.ModelSerializer:

  • Inherited from serializers.Serializer
  • The easy, the most commonly used

serializers.HyperLinkedModelSerializer:

  • Most intelligent
  • ModelSerializer subclass is, a plurality of attribute url
    • It can be dynamically generated links
    • Obtaining a single object needs to be configured the way, it requires a primary key as parameters and aliases
      • namespace, name
  • Configuration cumbersome

RESTframework of Double R

  1. Request
  • In Django request can only accept GET, POST parameters, PUT, PATCH parameters without making process, in the body of the incoming, interspersed with escape and tabs, needs its own processing
  • Request for the DRF been restructured to obtain parameters using request.data
    • acceptable data POST, PUT, PATCH parameters
  1. Response
  • Inherited from Django in SimpleTemplateResponse
  • You can return different content, depending on the client

views are two ways to convert Wrapping

  1. @api_view decorator (FBV way)

Use the FBV model, added before routing function

  • Required by appending the list of allowable requests method
    • The default http_method_names = None, only supports GET requests
  • Django will request the conversion of the request became restframework
  • The original HttpResponse normal compatible
  • Response can be used to return different content based on end customer
  • The method is similar to as_view (), the method of obtaining the name of the request, the judge is not there a method to the list, if it returns to the handler, implement support a request
  1. Inherited from APIView (CBV way)
  • Compatible with existing code that does not require big changes, the incoming data will be returned as the response, if the string is the string returned directly
  • APIView inherited from View
  • APIView implements the method name acquisition request, and then returns to the Handler, and in view of similar as_vie

Guess you like

Origin blog.csdn.net/qq_27114273/article/details/91517219