django-restframework-swagger 2.1.2(2.2.0也可以,UI更好看些,但是不方便测试,所以我选择2.1.2)
效果图
参数框:
class S2ViewList(GenericAPIView):#
serializer_class = S2createSerializer #指定序列化类,自动显示model body
schema = AutoSchema (
manual_fields=[
coreapi.Field (name='vxnet',required=False,location='query',description='',type='string'),
coreapi.Field (name='service_type',required=False,location='query',description='',
type='string'),
]
)
def get(self,request,format=None):
.....
def post(self, request,format=None):
.......
AutoSchema的参数对所有方法都一致,为了区分不同方法显示不同参数,参考AutoSchema源码,继承它写一个新类:
class RecycleSchema (AutoSchema):
"""
Overrides 'get_manual_fields()' to provide Custom Behavior X
"""
def __init__(self, manual_fields=None, delete_fields=None):
"""
Parameters:
* `manual_fields`: list of `coreapi.Field` instances that
will be added to auto-generated fields, overwriting on `Field.name`
"""
super (RecycleSchema, self).__init__ (manual_fields)
if manual_fields is None:
manual_fields = []
self._manual_fields = manual_fields
if delete_fields is None:
delete_fields = []
self._delete_fields = delete_fields
def get_manual_fields(self, path, method):
"""Example adding per-method fields."""
delete_fields = []
if method == 'DELETE':
delete_fields = self._delete_fields
manual_fields = super ().get_manual_fields (path, method)
return manual_fields + delete_fields
def get_delete_fields(self, path, method):
return self._delete_fields
view中:
class InstancesList(APIView):
"""
get:
获取回收站instances列表
delete:
彻底删除instance
"""
schema = RecycleSchema(
manual_fields=[
coreapi.Field(
name='Authorization',
required='True',
location='header',
description='Authentication header',
type='string'),
coreapi.Field(
name='DcCode',
required='True',
location='header',
description='dccode header')],
delete_fields=[
coreapi.Field(
name='instances',
required=True,
location="query",
description='主机id')])
若想实现response body也显示model,考虑使用drf-yasg,其使用openapi,swagger界面更完善(复杂):
https://github.com/axnsan12/drf-yasg/tree/23ebba420734d9760d2e60d4c3b057d7accc8996#code-generation