简体   繁体   English

如何使用 drf-yasg Swagger 手动自定义 DRF 视图的参数?

[英]How to manually customize parameters of DRF views using drf-yasg Swagger?

I am using drf-yasg package to integrate Swagger with DRF.我正在使用drf-yasg包将 Swagger 与 DRF 集成。

As documentation said I used @swagger_auto_schema decorator to manually customize auto-generated endpoints.正如文档所说,我使用@swagger_auto_schema装饰器来手动自定义自动生成的端点。 After a lot of tries I still can't figure out why there are no any changes.经过多次尝试,我仍然无法弄清楚为什么没有任何变化。

So, I tried to add extra query parameter to RetrieveUpdateAPIView :因此,我尝试向RetrieveUpdateAPIView添加额外的查询参数:

class MyCustomView(RetrieveUpdateAPIView):
    ...

    @swagger_auto_schema(
        manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)]
    )
    def retrieve(self, request, *args, **kwargs):
        ...

After all, nothing seems changed.毕竟,似乎什么都没有改变。 What exactly I have to do then?那我到底要做什么?

you have to add swagger_auto_schema in get method instead of retrieve.您必须在 get 方法中添加swagger_auto_schema而不是检索。

@swagger_auto_schema(
        manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)]
    )
    def get(self, request, *args, **kwargs):
        ...

A query_serializer parameter was added in 1.18 ( https://github.com/axnsan12/drf-yasg/pull/17 ).在 1.18 ( https://github.com/axnsan12/drf-yasg/pull/17 ) 中添加了query_serializer参数。

Example:例子:

    from rest_framework import serializers
    from rest_framework import viewsets
    from drf_yasg.utils import swagger_auto_schema
    
    class CustomParametersSerializer(serializers.Serializer):
        myparam = serializers.CharField(help_text="My manual querystring parameter")

    class MyViewSet(viewsets.ViewSet):
        @swagger_auto_schema(query_serializer=CustomParametersSerializer)
        def my_route(self, request):
            ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM