如何使用 drf-yasg 自动生成的 swagger 页面配置 "HTTPS" 方案?

How can I configure "HTTPS" schemes with the drf-yasg auto-generated swagger page?

我知道在传统的 swagger YAML 文件中,我们可以定义方案:

schemes:
  - http
  - https

//OR

schemes: [http, https]

但是,如何使用 drf-yasg 库对自动生成的 swagger 页面做同样的事情?

现在生成的swagger页面只有HTTP个方案,缺少HTTPS个。我尝试将 setting.py 中的 DEFAULT_API_URL 设置为 https://mybaseurl.com,但它似乎不起作用。

有解决办法。

urls.py 中定义 get_schema_view() 时,使用此代码:

schema_view = get_schema_view(
    openapi.Info( ... ),
    url='https://example.net/api/v1/', # Important bit
    public=True,
    permission_classes=(permissions.AllowAny,)
)

注意:您可以使用 https 或 http,因为更好地将此解决方案与环境变量一起用于不同的设置。

url='https://your_server_address/'

在 get_schema_view() 函数中带有 URL.

要在 swagger 中同时使用 httphttps 方案,您可以从 drf_yasg.generators 扩展 OpenAPISchemaGenerator

class BothHttpAndHttpsSchemaGenerator(OpenAPISchemaGenerator):
    def get_schema(self, request=None, public=False):
        schema = super().get_schema(request, public)
        schema.schemes = ["http", "https"]
        return schema

所以现在您可以将它用作 generator_class for get_schema_view()

schema_view = get_schema_view(
    openapi.Info( ... ),
    public=True,
    generator_class=BothHttpAndHttpsSchemaGenerator, # Here
    permission_classes=(AllowAny,)
)