欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Powered by Django REST Swagger

程序员文章站 2022-07-02 20:56:59
...

Powered by Django REST Swagger

#1 环境

Python==3.7.6
Django==2.0.7
django-rest-swagger==2.2.0

安装swagger

pip install django-rest-swagger

#2 使用指南

#2.1 注册app

INSTALLED_APPS = [
    ...
    'rest_framework_swagger',
    ...
]

#2.2 使用

from rest_framework.schemas import get_schema_view # 导入辅助函数get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer,OpenAPIRenderer # swagger
schema_view = get_schema_view(title='API',renderer_classes=[SwaggerUIRenderer,OpenAPIRenderer])

urlpatterns = [
    path('', schema_view, name='docs'),   # 配置swagger的url路径
    ...
]

启动Django,在浏览器输入ip:端口号即可访问swagger

Powered by Django REST Swagger

我的项目一般是一个视图对应一个接口,如果一个视图对应多个请求,可以写成以下格式

from django.shortcuts import render
from django.contrib.auth.models import User,Group
from rest_framework import viewsets
from API.serializers import UserSerializer,GroupSerializer

# Create your views here.

# viewsets通过serializer_class找到对应的serializers
class UserViewSet(viewsets.ModelViewSet):
    '''
        retrieve:
            Return a user instance.

        list:
            Return all users,ordered by most recent joined.

        create:
            Create a new user.

        delete:
            Remove a existing user.

        partial_update:
            Update one or more fields on a existing user.

        update:
            Update a user.
    '''
    queryset = User.objects.all()   # 将User的所有对象赋给queryset,并返回对应值
    serializer_class = UserSerializer   # 指向UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    '''
        retrieve:
            Return a group instance.

        list:
            Return all groups,ordered by most recent joined.

        create:
            Create a new group.

        delete:
            Remove a existing group.

        partial_update:
            Update one or more fields on a existing group.

        update:
            Update a group.
    '''
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

Powered by Django REST Swagger