django配置swagger

前言:

在SpringBoot常用的接口测试,接口文档生成的工具 swagger


一、安装

pip install    drf-yasg

pip  install  djangorestframork

二、子django项目中配置

settings.py

INSTALLED_APPS = [
        ....

        'rest_framework',

        'drf_yasg',  # swagger 接口 'app1',
        .....

]

urls.py

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
    openapi.Info(
        title="Snippets API",
        default_version='v1',
        description="Test description",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="[email protected]"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
)

from django.contrib import admin
from django.urls import path, re_path
from app1 import views as app_views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('demo/',app_views.demo,name="dmeo"),
    # 对测试人员更友好
    re_path(r'^$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),#《----------
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),#《----------
    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),#《----------
    # 对开发人员更友好
    re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),#《----------

]

启动项目:

e6a1d50543e846d28bdb20ad9abed319.png

三、通过 rest_framework实现接口

rest_framework的简单使用

安装:

pip install djangorestframework
pip install django-filters
INSTALLED_APPS = [
     ....
    'rest_framework',#
    'django_filters', # 条件过滤
    'drf_yasg',  # swagger 接口
    'app1',# 测试APP
]

models.py

from django.db import models

'''
书籍表 Book:title 、 price 、 pub_date 、 publish(外键,多对一) 、 authors(多对多)
出版社表 Publish:name 、 city 、 email
作者表 Author:name 、 age 、 au_detail(一对一)
作者详情表 AuthorDetail:gender 、 tel 、 addr 、 birthday
'''
# Create your models here.
class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish", on_delete=models.CASCADE)
    authors = models.ManyToManyField("Author")


class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=64)
    email = models.EmailField()


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.SmallIntegerField()
    au_detail = models.OneToOneField("AuthorDetail", on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    gender_choices = (
        (0, "女"),
        (1, "男"),
        (2, "保密"),
    )
    gender = models.SmallIntegerField(choices=gender_choices)
    tel = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    birthday = models.DateField()

 SQL语句

insert into app1_publish(id,name,city,email) values (1,"华山出版社", "华山", "[email protected]"), (2,"明教出版社", "黑木崖", "[email protected]");
insert into app1_publish(id,name,city,email) values (3,"嵩山出版社", "嵩山", "[email protected]");
insert into app1_publish(id,name,city,email) values (4,"泰山出版社", "泰山", "[email protected]");
insert into app1_publish(id,name,city,email) values (5,"恒山出版社", "恒山", "[email protected]");
insert into app1_publish(id,name,city,email) values (6,"衡山出版社", "衡山", "[email protected]");
insert into app1_publish(id,name,city,email) values (7,"祁连山出版社", "祁连山", "[email protected]");
insert into app1_publish(id,name,city,email) values (8,"庐山出版社", "庐山", "[email protected]");
insert into app1_publish(id,name,city,email) values (9,"峨眉山版社", "峨眉山", "[email protected]");
insert into app1_publish(id,name,city,email) values (10,"黄山出版社", "黄山", "[email protected]");
insert into app1_publish(id,name,city,email) values (11,"五台山出版社", "五台山", "[email protected]");

insert into app1_authordetail(id,gender,tel,addr,birthday) values (1,1,13432335433,"华山","1999-01-09"), (2,1,13943454554,"黑木崖","1999-01-09"), (3,0,13878934322,"黑木崖","1999-01-09");

insert into app1_author(id,name,age,au_detail_id) values (1,"令狐冲",25,1);
insert into app1_author(id,name,age,au_detail_id) values (2,"任我行",58,2);
insert into app1_author(id,name,age,au_detail_id) values (3,"任盈盈",23,3);

insert into app1_book(id,title,price,pub_date,publish_id) values (1,"笑傲江湖",23.30,'1969-05-06',1);

insert into app1_book_authors(id,book_id,author_id) values (1,1,1);

 序列化器   ModelsSerializers.py

# -*- coding: utf-8 -*-
'''
@date:2023/6/2 10:46
@email:[email protected]
@author:小纯
@Content: 序列化
'''
from .models import *
from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields= "__all__" # 全部
        # fields = ['id','book_name','press','type']
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model= Publish
        fields= "__all__" # 全部
        # fields = ['id','book_name','press','type']
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model= Author
        fields= "__all__" # 全部
        # fields = ['id','book_name','press','type']
class AuthorDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model= AuthorDetail
        fields= "__all__" # 全部
        # fields = ['id','book_name','press','type']

查询条件过滤器 Filter.py

# -*- coding: utf-8 -*-
'''
@date:2023/6/2 15:52
@email:[email protected]
@author:小纯
@Content: 条件过滤器
'''

import django_filters
from django_filters.rest_framework import FilterSet
from .models import *


class PushFilter(FilterSet):
    """
    出版社 简单序过滤器
    field_name(必选):模型类的属性
    lookup_expr(可选):判断条件
        iexact:表示精确匹配, 并且忽略大小写
        icontains:表示模糊查询(包含),并且忽略大小写
        exact:表示精确匹配
        gte:用于规定范围,大于等于
        lte: 用于范围,小于等于
    method: 自己定义一个方法
    help_text: 帮助说明
    """
    name = django_filters.CharFilter(lookup_expr='icontains')
    city = django_filters.CharFilter(lookup_expr='icontains')
    email = django_filters.CharFilter(lookup_expr='exact')

    # 自定义方法
    # deptId = django_filters.CharFilter(method='filter_deptId')
    # def filter_deptId(self, queryset, name, value):
    #     return queryset.filter(dept__id__in=get_dept(dept_id=value))

    class Meta:
        model = Publish
        fields = ('name', 'city', 'email')

view.py

from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from .ModelsSerializers import *
from .models import *
from utils.pages_tools import MyFormatResultsSetPagination
from .Filter import *
# Create your views here.



class BookView(ModelViewSet):
    queryset = Book.objects.all().order_by('id')
    serializer_class = BookSerializer
    pagination_class  = MyFormatResultsSetPagination

class PublishView(ModelViewSet):
    queryset = Publish.objects.all().order_by('id')
    # 2、serializer_class 是固定的序列化器 类
    serializer_class = PublishSerializer
    pagination_class  = MyFormatResultsSetPagination
    # 过滤器
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    # 模糊匹配查询
    filterset_class = PushFilter
    # 支持精准匹配的字段
    filterset_fields = ('name', 'city', 'email')

class AuthorView(ModelViewSet):
    queryset = Author.objects.all().order_by('id')
    serializer_class = AuthorSerializer
    pagination_class  = MyFormatResultsSetPagination

url.py

# -*- coding: utf-8 -*-
'''
@date:2023/6/2 10:45
@email:[email protected]
@author:小纯
@Content:
'''

from django.urls import path, re_path
from .views import *

# 最终封装的内容
from rest_framework.routers import DefaultRouter
from .views import *
router = DefaultRouter() # 可以处理视图的路由器
router.register('book',BookView)# 向路由中注入视图
router.register('publish',PublishView)# 向路由中注入视图
router.register('author',AuthorView)# 向路由中注入视图


urlpatterns = [

]

urlpatterns+=router.urls # 将路由添加到  全局路由上

cc3fd88808ad4357af7a9e09deb52922.png

15d2e6ffc8ce44b4a11418ec04695b52.png 

猜你喜欢

转载自blog.csdn.net/weixin_51715424/article/details/130981102