在使用带有django-rest-swagger的APIView时,如何为POST请求指定参数

时间:2016-12-12 15:55:04

标签: django django-rest-framework swagger-2.0

在Django REST Swagger(2.1.0)的最新版本中,YAML文档字符串已被弃用。我无法大摇大摆地展示POST请求参数。

这是我的观点

class UserAuthenticationView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = UserAuthenticationSerializer(data=self.request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK)

        return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)

这是我的Serializer

class UserAuthenticationSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if user:

                if not user.is_active:
                    msg = 'User account is disabled.'
                    raise serializers.ValidationError(msg, code='authorization')

            else:
                msg = 'Unable to log in with provided credentials.'
                raise serializers.ValidationError(msg, code='authorization')

        else:
            msg = 'Must include "username" and "password".'
            raise serializers.ValidationError(msg, code='authorization')

        attrs['user'] = user
        return attrs

这是我在生成的enter image description here

中获得的内容

我没有获得包含POST数据字段的表单。我怎么做到的?

3 个答案:

答案 0 :(得分:14)

django-rest-swagger 使用 rest_framework.schemas.SchemaGenerator 生成架构, SchemaGenerator 使用 get_serializer_fields 获取视图的序列化信息。 get_serializer_fields检查视图是否有 get_serializer 方法来生成表单。 GenericAPIView 提供 get_serializer ,因此继承它就足够了。

GenericAPIView继承视图,而不是简单APIView。并使用适当的序列化程序

添加serializer_class属性
from rest_framework.generics import GenericAPIView 

class UserAuthenticationView(GenericAPIView):

    serializer_class = UserAuthenticationSerializer

    def post(self, request, *args, **kwargs):
        serializer = UserAuthenticationSerializer(data=self.request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            return Response({'token': user.auth_token.key}, status=status.HTTP_200_OK)    
        return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED)

答案 1 :(得分:3)

这是其余的框架获取模式代码(它的一部分):

def get_serializer_fields(self, path, method, view):
    """
    Return a list of `coreapi.Field` instances corresponding to any
    request body input, as determined by the serializer class.
    """
    if method not in ('PUT', 'PATCH', 'POST'):
        return []

    if not hasattr(view, 'get_serializer'):
        return []

    serializer = view.get_serializer()

    if isinstance(serializer, serializers.ListSerializer):
        return [
            coreapi.Field(
                name='data',
                location='body',
                required=True,
                type='array'
            )
        ]
...

正如您所看到的 - 如果您在视图上定义get_serializer方法,它将返回UserAuthenticationSerializer

- 编辑 -

忘了:快乐的编码。

答案 2 :(得分:2)

使用django-rest-swagger == 2.2.0的自定义ViewSet的工作示例:

from rest_framework import viewsets
from rest_framework.schemas import AutoSchema
from rest_framework.compat import coreapi, coreschema
from rest_framework.decorators import action


class DeviceViewSchema(AutoSchema):
    """
    Schema customizations for DeviceViewSet
    """

    def get_manual_fields(self, path, method):
        extra_fields = []
        if path.endswith('/send_command/'):
            extra_fields = [
                coreapi.Field(
                    "command",
                    required=True,
                    location="form",
                    schema=coreschema.String()
                ),
                coreapi.Field(
                    "params",
                    required=False,
                    location="form",
                    schema=coreschema.String()
                ),
            ]
        manual_fields = super().get_manual_fields(path, method)
        return manual_fields + extra_fields


class DeviceViewSet(viewsets.ViewSet):
    lookup_field = 'channel'
    lookup_value_regex = '[\w-]+'

    schema = DeviceViewSchema()

    @action(methods=['post'], detail=True, url_name='send_command')
    def send_command(self, request, channel):
        """
        Send command to device

        Parameters:
        - command: string
        - params: string (JSON encoded list or dict)
        """
        ...

最终结果是:

enter image description here