如何在 django 应用程序的 swagger ui 中添加自定义字段?

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

对于每个请求,api 端点都需要标头名称“VENDOR”。我需要在 Django swagger ui 中创建一个字段来添加 VENDOR 值并将其附加到每个请求的标头中。

我尝试在 Django 设置中自定义 swagger 设置,但没有成功

我想要类似图片中的东西,但必须是现场供应商并添加到其请求中

图片链接

django swagger
1个回答
0
投票

通过在 templates/spectaulous/swagger-ui.html 中创建文件来扩展 swagger-ui.html

这里我添加了一个名为供应商的字段,并添加到每个请求的标头中。

<!DOCTYPE html>
<html lang="eng">
  <head>
    <title>API Documentation</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="{{ swagger_ui_css }}" />
    <style>
      html {
        box-sizing: border-box;
        overflow-y: scroll;
      }

      *,
      *:after,
      *:before {
        box-sizing: inherit;
      }

      body {
        background: #fafafa;
        margin: 0;
        padding: 20px;
      }

      .vendor-input {
        margin-bottom: 10px;
        display: none;
      }

      .swagger-ui .topbar {
        display: none;
        /* Hide the default top bar */
      }
    </style>
  </head>
  <body>
    <div id="swagger-ui"></div>
    <!-- Vendor input field placed after the API title and description -->
    <div class="vendor-input">
      <label for="vendor">Vendor:</label>
      <input type="text" id="vendor" name="vendor" />
    </div>
    <script src="{{ swagger_ui_bundle }}"></script>
    <script src="{{ swagger_ui_standalone }}"></script>
    <script>
      window.onload = function() {
        const vendorInputDiv = document.querySelector('.vendor-input');
        const ui = SwaggerUIBundle({
          url: "/api/schema/",
          dom_id: '#swagger-ui',
          presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIStandalonePreset
          ],
          layout: "StandaloneLayout",
          onComplete: function() {
            // Move the vendor input field after the API title and description
            const info = document.querySelector('.swagger-ui .info');
            if (info) {
              info.appendChild(vendorInputDiv);
              vendorInputDiv.style.display = 'block';
            }
          },
          requestInterceptor: function(request) {
            const vendor = document.getElementById('vendor').value || 'test.com';
            if (vendor) {
              request.headers['VENDOR-SITE'] = vendor;
              request.headers['X-CSRFToken'] = "{{csrf_token }}"
            }
            return request;
          }
        });
        window.ui = ui;
      };
    </script>
  </body>
</html>

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