如何使用 drf-spectaulous 记录服务器发送事件

问题描述 投票:0回答:1

我正在从 drf-yasg 迁移到 drf-spectaulous,但在迁移服务器发送事件/StreamingHttpResponse 的文档时遇到问题。这是在 drf-yasg 中运行的代码。你会如何用 drf-spectaulous 来写这个?

class EventStreamData(SwaggerAutoSchema):
    def get_produces(self):
        return ["text/event-stream"]

    def get_consumes(self):
        return ["text/event-stream"]


@api_view(["GET"])
@renderer_classes([EventStreamRenderer]) 
    response = StreamingHttpResponse(event_stream(), content_type="text/event-stream")
    response['Cache-Control'] = 'no-cache'
    return response


swagger_info = extend_schema(methods='GET', auto_schema=EventStreamData, tags=['2. Server Sent Events'],
                                   responses={200: openapi.Response(
                                       description="text/event-stream",
                                       examples={
                                           "text/event-stream":
                                               "data: { "
                                               "'field1': '', "
                                               "'field2': '', "
                                               "'field3': '', "
                                               "'field4': '', "
                                               "}"

                                       })
                                   })
data_stream = swagger_info(data_stream)
django swagger swagger-ui drf-yasg drf-spectacular
1个回答
0
投票

我们可以使用

OpenApiWebhook
中的
from drf_spectacular.utils import OpenApiCallback, extend_schema, OpenApiWebhook

例如

your_event = OpenApiWebhook(
    name="name of event",
    decorator=extend_schema(
        summary="Summary",
        description= "description of the event"
        "variation.",
        tags=["webhooks"],
        request=<Schema or serializer>,
        responses=<Response schema or serializer>,
    ),
)

然后在settings.py中

SPECTACULAR_SETTINGS = {
...
"WEBHOOKS": [<path to the webhook>]
...
}

这将在 API 文档中列为事件。

© www.soinside.com 2019 - 2024. All rights reserved.