ViewSet操作

时间:2017-11-08 13:51:06

标签: django django-rest-framework swagger openapi

我想为我的DRF项目生成swagger(OpenAPI)架构。

如何将查询参数规范添加到生成的架构中?

看一下FileViewSet.list方法。这里应记录request.GET参数project(必需),但自动模式生成错过了它。

以下是api项目示例:

# views.py

class FileSerializer(serializers.ModelSerializer):    
    class Meta:
        model = File
        fields = ('name', 'id', 'project')


class FileViewSet(viewsets.ModelViewSet):
    queryset = File.objects.all()
    serializer_class = FileSerializer

    def list(self, request):
        project = request.GET.get("project", None)

        qs = self.get_queryset().filter(project=project)


router = routers.DefaultRouter(trailing_slash=False)
router.register(r'^file$', FileViewSet)


# OpenAPI Schema generation

class SwaggerRenderer(renderers.BaseRenderer):
    media_type = 'application/openapi+json'
    format = 'swagger'

    def render(self, data, media_type=None, renderer_context=None):
        codec = OpenAPICodec()
        return codec.dump(data)

schema_view = get_schema_view(
    title='API',
    public=True,
    renderer_classes=[SwaggerRenderer],
    authentication_classes=[],
    permission_classes=[AllowAny],
    patterns=router.urls,
)

api_urls = router.urls + [url(r'^schema$', schema_view, name="schema")]

然后在api_urls中加入urls.py

# urls .py

from .views import api_urls

urlpatterns = [
    url(r'^v1/', include(api_urls, namespace="v1")),
]

DRF coreapi ManualScheme docs手动记录APIView以添加自定义字段,但ViewSet没有文档。

2 个答案:

答案 0 :(得分:0)

我认为你配置有点不对劲。我在我的项目中做的是从get_swagger_view导入rest_framework_swagger.views并将视图添加到项目网址中,它就像一个魅力。

示例

# project/urls.py

from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='My API')

urlpatterns = [
    # other urls...
    url(r'^schema/$', schema_view),
]

参考:Swagger Docs

注意get_swagger_view是获取基本配置的快捷方式。请参阅advanced usage部分以获得更多控制权。

答案 1 :(得分:0)

ManualSchema的{​​{1}}相同,还有APIViewAutoSchema完美配合,甚至允许覆盖自动生成的路径参数,例如ViewSet。例如:

id

这会将路径参数import coreapi import coreschema from rest_framework.schemas import AutoSchema ... class YourViewSet(...): schema = AutoSchema( manual_fields=[ coreapi.Field('id', required=True, location='path', description='A unique integer value identifying specific your-model-name.', schema=coreschema.Integer(), ), ] ) 添加(或在这种情况下覆盖)架构,并以摇摇欲坠的方式生成验证。 enter image description here