6

我需要将 API 文档添加到我的项目中。我使用 swagger 编辑器编写了我的自定义模式,现在我有一个 YAML 文件,如下所示:

swagger: "2.0"
info:
  description: "This is the documentation of Orion Protocol API"
  version: "1.0.0"
  title: "Orion Protocol API"
host: "127.0.0.1:8000"
basePath: "/api/"
paths:
  /api/decode:
    post:
      tags:
      - "pet"
      summary: "Decode the payload"
      consumes:
      - "application/json"
      produces:
      - "application/json"
      parameters:
      - in: "body"
        name: "body"
        description: "Packet data"
        required: true
        schema:
          $ref: "#/definitions/PacketData"
      responses:
        "405":
          description: "Invalid input"

  /api/encode:
   post:
     description: "Encoding configuration parameters for the devices"
     produces:
     - "string"
     parameters:
     - in: "body"
       name: "body"
       description: "Addresses and values of configuration parameters"
      required: true
       schema:
         $ref: "#/definitions/ConfigPayload"
     responses:
       "405":
         description: "Invalid input"


  definitions:
    PacketData:
      type: "object"
      required:
      - "payload"
      properties:
     payload:
       type: "string"
       description: "Packet string starting with 78"
       example: "78010013518BB325140400000500000AAA0000002A6E0000004AC05D00006A00000000"
    ConfigPayload:
        type: "object"
       properties:
          Addresses of the configuration parameter:
            type: "string"
            description: "According to the documentation of configuration protocol"
            example: "542"

现在我怎样才能将它添加到项目中?它应该在项目中的什么位置?视图可以呈现这个文件吗?我需要有以下路径:

urlpatterns = [
     path('documentation/', some-view-that-will-render-yaml)
]
4

1 回答 1

5

我找到了一个解决方案,这很容易。我们需要将 yaml 转换为 json 并将其保存在静态文件夹中。然后:urls.py

urlpatterns =  [
    ...
    path('swagger-ui/', TemplateView.as_view(
        template_name='swagger-ui.html',
        extra_context={'schema_url': 'openapi-schema'}
    ), name='swagger-ui'),
]

模板/swagger-ui.html:

{% load static %}
<html>
  <head>
    <title>Documentation</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
  </head>
  <body>
    <div id="swagger-ui"></div>
    <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
    <script>

   const ui = SwaggerUIBundle({
    url: "{% static 'swagger.json' %}" ,
    dom_id: '#swagger-ui',
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIBundle.SwaggerUIStandalonePreset
    ]
  })
    </script>
  </body>
</html>

并将您的自定义模式另存为 json 在静态文件夹中。作品!

于 2020-06-10T08:24:24.247 回答