hualinux dj3 2.3: use drf to rewrite django to connect to mysql

table of Contents

One, django uses drf to rewrite ideas

Two, refactor Django code

2.1 Django installation and configuration

2.2 Create drf serialization

2.3 Use the view set APIView

2.4 Add url mapping

Three, operation effect


This article rewrites the project written as json in " Connecting to mysql8.0 database " into drf mode.
The required knowledge points are all the contents of the drf official tutorial tutorial.
There is also the view related to the api guide (API Guide) next to it

One, django uses drf to rewrite ideas

The idea of ​​changing the json returned by ordinary django into drf is as follows:

1. Serialization serializers: We use serialization serializers in the drf framework instead of django, mainly to convert the python data type to json
2. View APIView view set viewsets: drf uses class-based views. I first use the @api_view() decorator in apiView , which is written at the top of the function, indicating that this is a drf APIView instead of a django view.
3. URL configuration routing route: This function is mainly related to the class (view set), and the url of django is related to the function.
What I use here is a function, not a class, so route is not used.
4. Others, I did not add permissions and the like, delete them. The paging function is optional, I added it.

Two, refactor Django code

Use the drf framework to rewrite the previous " Connect to mysql8.0 database ", the operation is as follows:

2.1 Django installation and configuration

The installation and configuration are installed in accordance with the " django REST framework (drf) installation ", I will not go into details here.

2.2 Create drf serialization

I created a file named serializers.py in the app with the following content:

from rest_framework import serializersfrom app.models import Stu  class StudentSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model=Stu        fields = '__all__'
If you don’t understand, you can check the serialization part of the tutorial or the ModelSerializers part of the API guide .

2.3 Use the view set APIView

REST framework provides an APIView class, which is a subclass of Django's View class.
The APIView class has the following differences from the general View class:
  • The request passed into the processing method will not be an instance of Django's HttpRequest class, but an instance of REST framework's Request class.
  • The processing method can return REST framework's Response instead of Django's HttpRequest. The view manages the content protocol and sets the correct renderer for the response.
  • Any APIException will be caught and passed to the appropriate response.
  • Incoming requests will be authenticated, and appropriate permissions and/or throttling checks will be run before the request is dispatched to the processing method.
Using the APIView class is very similar to using the general View class. Usually, incoming requests will be dispatched to appropriate processing methods such as .get() or .post. In addition, many attributes will be set on the classes that control various aspects of the API strategy.

The app/views.py code is modified as follows:

import jsonfrom rest_framework.decorators import api_viewfrom app.models import Stufrom app.serializers import StudentSerializer @api_view()def findStuBySid(request, stuSid):    querysets = Stu.objects.filter(sid=stuSid)    # 可以序列化查询结果集(querysets)而不是模型实例。    # 我们只需要为serializer添加一个many=True标志。    serializer = StudentSerializer(querysets, many=True)    # 结果为有序列字典,只有一个结果,所以取第1个    #[{"id": 11, "sid": "011", "name": "fly", "yuWen": "90.0", "shuXue": "89.0"}]    res = json.dumps(serializer.data[0])    return HttpResponse(res)

The result set is used in the above, so we need to use many=Ttrue. If we only check one record, we can actually use get, so I modify it and the code becomes:

@api_view()def findStuBySid(request, stuSid):    querysets = Stu.objects.get(sid=stuSid)    # 可以序列化查询结果集(querysets)而不是模型实例。    # 我们只需要为serializer添加一个many=True标志。    serializer = StudentSerializer(querysets)    res = json.dumps(serializer.data)    print(serializer.data)    return HttpResponse(res)

2.4 Add url mapping

app/urls.py add content

        path('sid/<str:stuSid>', views.findStuBySid, name='stuBySid'),

Three, operation effect

Run django, enter http://127.0.0.1:8000/sid/001 in the browser  , the effect is as follows:

PS: If there is no backslash at the end, it cannot be written as  http://127.0.0.1:8000/sid/001/ , otherwise it will report 404