1

因此,我正在使用以下代码记录以下代码drf-spectacular

from rest_framework import response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status

from drf_spectacular.utils import extend_schema, OpenApiParameter

def passcode_generator:
    return 0 # placeholder


@extend_schema(
    parameters=[
        OpenApiParameter(name="callsign", required=True, type=str),
    ],
    description="Get an APRS-IS passcode for a given callsign",
)
@api_view(["POST"])
@permission_classes([AllowAny])
def get_passcode(request):
    callsign = request.data.get("callsign", None)
    if callsign is None:
        raise Response(
            {"error": "Missing callsign"}, status=status.HTTP_400_BAD_REQUEST
        )
    return Response({"passcode": passcode_generator(callsign)})

我不明白该怎么做是如何记录响应。OpenApiResponse即,有drf_spectacular.utils但文档很薄。我如何用这个系统记录我的 API 的响应?

4

1 回答 1

1

如果你没有Serializer,你可以使用inline_serializer

from drf_spectacular.utils import extend_schema, OpenApiParameter, inline_serializer

# ...

@extend_schema(
    parameters=[
        OpenApiParameter(name="callsign", required=True, type=str),
    ],
    description="Get an APRS-IS passcode for a given callsign",
    responses={
       200: inline_serializer(
           name='PasscodeResponse',
           fields={
               'passcode': serializers.CharField(),
           }
       ), 
       400: OpenApiResponse(description='Missing callsign'),
    }
)
@api_view(["POST"])
@permission_classes([AllowAny])
def get_passcode(request):
    callsign = request.data.get("callsign", None)
    # ...
于 2022-01-01T18:40:54.960 回答