Django implements interface automation platform (12) custom function module DebugTalks serializer and view [continuously updated]

Previous chapter:

Django implements the interface automation platform (11) project module Projects serializer and view [continuously updated]_Do test meow sauce blog-CSDN blog

This chapter is a breakdown of the project. When viewing the content of this chapter, it should be viewed in conjunction with the overall project code:

Python django vue httprunner implements interface automation platform (final version)

1. DebugTalks background and related interfaces

1.1 DebugTalks application

Interface automation, the driver uses httprunner==1.0 version.

In httprunner, there is a debugtalks.py file to write custom functions.

So when we create a project, a debugtalks.py file will be automatically created. A project corresponds to a debugtalks.py file.

1.2 DebugTalks interface

request method URI corresponding action Realize function
GET /debugtalks/ .list() Query the debugtalk list
GET /debugtalks/{id}/ .retrieve() Retrieve detailed data of a debugtalk
PUT /debugtalks/{id}/ update() Update all fields in a piece of data
PATCH /debugtalks/{id}/ .partial_update() Update some fields in a piece of data

2. DebugTalks interface

debugtalks is a python file

2.1 List of built-in function files.list  ()

 Built-in function files, generated by accompanying projects. Creating a project automatically creates a debugtalk.py file. Deleting a project automatically deletes the corresponding debugtalk.py file.

GET /debugtalks/ .list() Query the debugtalk list

2.2 View the built-in function  file.retrieve()

GET /debugtalks/{id}/ .retrieve() Retrieve detailed data of a debugtalk

click file

 

 

2.3 Update built-in function files 

PUT /debugtalks/{id}/ update() Update all fields in a piece of data

Click Save at the bottom to update the file.

2.4 Create and delete

Creation and deletion are accompanied by project creation and deletion, so the creation and deletion of built-in files are not implemented through interfaces.

3. Model class model

from django.db import models

from utils.base_models import BaseModel


class DebugTalks(BaseModel):
    id = models.AutoField(verbose_name='id主键', primary_key=True, help_text='id主键')
    name = models.CharField('debugtalk文件名称', max_length=200, default='debugtalk.py', help_text='debugtalk文件名称')
    debugtalk = models.TextField(null=True, default='#debugtalk.py', help_text='debugtalk.py文件')
    project = models.OneToOneField('projects.Projects', on_delete=models.CASCADE,
                                   related_name='debugtalks', help_text='所属项目')

    class Meta:
        db_table = 'tb_debugtalks'
        verbose_name = 'debugtalk.py文件'
        verbose_name_plural = verbose_name
        ordering = ('id',)

    def __str__(self):
        return self.name

This code defines a Django model (Model) class named DebugTalks, representing a debugtalk.py file.

This model class inherits from BaseModel and contains the following fields:

  • id: auto-incremented primary key field, the type is AutoField.
  • name: The name of the debugtalk file, the type is CharField.
  • debugtalk: The content of the debugtalk.py file, the type is TextField.
  • project: The project associated with the debugtalk.py file, using a one-to-one (OneToOne) relationship, the type is a ForeignKey (ForeignKey) field, and is associated with the projects.Projects model.

In addition, the model class also defines the following metadata (Meta):

  • db_table: specifies the name of the table in the database as tb_debugtalks.
  • verbose_name: The name displayed on the background management page of the model is "debugtalk.py file".
  • verbose_name_plural: The plural name of the model displayed in the background management page is also "debugtalk.py file".
  • ordering: Specifies to sort in ascending order according to the id field.

Through this model class, a table named tb_debugtalks can be created in the database to store the information of the debugtalk.py file and associate it with the project.

 

Fourth, the serializer class

from rest_framework import serializers

from .models import DebugTalks


class DebugTalksModelSerializer(serializers.ModelSerializer):
    project = serializers.SlugRelatedField(slug_field='name', read_only=True)

    class Meta:
        model = DebugTalks
        exclude = ('create_datetime', 'update_datetime',)
        extra_kwargs = {
            'debugtalk': {
                'write_only': True
            }
        }


class DebugTalksSerializer(serializers.ModelSerializer):

    class Meta:
        model = DebugTalks
        fields = ('id', 'debugtalk')

Two serializer classes are defined:

1. The DebugTalksModelSerializer class inherits from DRF's ModelSerializer. in:

  • The project field uses SlugRelatedField to display the project field associated with the DebugTalks model as a name attribute, and it is read-only (read_only=True).
  • The model specified in the Meta inner class is DebugTalks, and the create_datetime and update_datetime fields are excluded.
  • extra_kwargs defines extra attributes for the debugtalk field, here it is set to write-only (write_only=True).

2. The DebugTalksSerializer class also inherits from DRF's ModelSerializer. in:

  • The model specified in the Meta internal class is DebugTalks, and only contains two fields: id and debugtalk.

These serializers can be used to convert DebugTalks model instances to JSON-formatted data, or to deserialize JSON data to DebugTalks model instances. By defining different fields and attributes, data can be validated, created, and updated to meet specific needs.

5. View

from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework import permissions
from .models import DebugTalks
from rest_framework import mixins
from . import serializers


class DebugTalksViewSet(mixins.ListModelMixin,
                        mixins.RetrieveModelMixin,
                        mixins.UpdateModelMixin,
                        viewsets.GenericViewSet):

    queryset = DebugTalks.objects.all()
    serializer_class = serializers.DebugTalksModelSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        return serializers.DebugTalksSerializer if self.action == 'retrieve' else self.serializer_class

First the necessary libraries and modules are imported:

  • from rest_framework import viewsets imports DRF's viewsets.
  • from rest_framework.decorators import action imports DRF decorators for defining custom actions.
  • from rest_framework import permissions imports the permission class of DRF.
  • from .models import DebugTalks imports the DebugTalks model class in the current project.
  • from rest_framework import mixins imports DRF's Mixin class.
  • from . import serializers imports the serializers in the current project.

Then a DebugTalksViewSet class is defined, which inherits various Mixin classes and GenericViewSet classes provided by DRF. in:

  • mixins.ListModelMixin provides list display function.
  • mixins.RetrieveModelMixin provides a detailed display function.
  • mixins.UpdateModelMixin provides update functionality.
  • viewsets.GenericViewSet is a generic viewset class.

The following properties and methods are defined in the class:

  • The queryset attribute specifies the query set of the view set, that is, the data set that needs to be operated. Here is DebugTalks.objects.all(), which means to obtain all instances of the DebugTalks model.
  • serializer_class specifies the serializer class used by default as serializers.DebugTalksModelSerializer.
  • permission_classes specifies the default permission class as permissions.IsAuthenticated, which means that only authenticated users can access the view set.

Next, a custom method get_serializer_class() is defined to determine which serializer class to use according to different actions. If the action is retrieve (details are shown), use serializers.DebugTalksSerializer, otherwise use the default serializer class.

Through these configurations and definitions, the DebugTalksViewSet class can provide list display, detail display and update functions, and select the appropriate serializer class for data serialization and deserialization operations according to different actions. At the same time, the view set also has permission control, and only authenticated users can access it.

 

Guess you like

Origin blog.csdn.net/qq_39208536/article/details/131748312