我应该如何在drf-yasg生成的自动化Swagger页面中配置“HTTPS”方案?

11

我知道在传统的Swagger YAML文件中,我们可以使用以下方式定义模式:

schemes:
  - http
  - https

//OR

schemes: [http, https]

然而,我该如何使用drf-yasg库自动生成的Swagger页面完成同样的操作呢?

现在,生成的Swagger页面只包含HTTP协议,但是缺少HTTPS协议。我已经尝试将setting.py中的DEFAULT_API_URL设置为https://mybaseurl.com,但似乎没有生效。


有关此问题有进展吗?我也遇到了同样的问题。 - compguy24
4个回答

21

要在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

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

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

此外,您可以使用request对象动态设置方案:if request: schema.schemes = ["https"] if request.is_secure() else ["http"] - undefined

15

有一个解决方案。

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,因此最好使用环境变量将此解决方案用于不同的设置。

2
现在它适用于https,但如果我想实现http和https两者都怎么办? - R.yan

0

在Swagger页面中使用SECURE_PROXY_SSL_HEADER配置是另一种实现https协议的方法。

假设您的Django REST API位于一个执行SSL终止的Nginx后面,您可以让Nginx将X-Forwarded-Proto: https转发到您的Django应用程序(根据您的设置,Nginx可能已经默认转发此标头)。使用以下配置,您的Django应用程序将意识到它位于SSL终止的Nginx后面,当存在该标头时,Django的内部函数is_secure()将返回True请参阅Django SSL设置

一旦is_secure()返回True,Swagger页面的协议将自动变为https

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

我喜欢这种方法,因为它不需要硬编码URL甚至从环境变量配置URL。此外,is_secure()函数在其他地方内部也被使用,因此希望该函数能够按照理想情况正常工作。


0

放置

url='https://your_server_address/'

在get_schema_view()函数中使用URL。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接