如何在 drf_yasg 中将方案从 HTTP 更改为 HTTPS?

Art*_*ski 5 python django django-rest-framework openapi drf-yasg

我正在使用drf_yasgswagger 文档。当我在 AWS Application Load Balancer 后面发布我的 DRF 应用程序并将侦听器设置为侦听 443 HTTPS 并重定向到运行 DRF 的 EC2 时,swagger UI 试图将请求发送到端点http://example.com/status而不是例如https://example.com/status. 这会产生一个谷歌浏览器错误:

swagger-ui-bundle.js:71 Mixed Content: The page at 'https://example.com/swagger#/status/status_list' was loaded over HTTPS, but requested an insecure resource 'http://example.com/status'. This request has been blocked; the content must be served over HTTPS.
Run Code Online (Sandbox Code Playgroud)

所以我解决这个问题的解决方案是在drf_yasg.views.get_schema_view. 所以我的代码看起来像:

schema_view = get_schema_view(
    openapi.Info(
        title="Server Api Documentation",
        default_version="v1",
        description="",
    url="http://example.com/status"
)

# noinspection PyUnresolvedReferences
swagger_patterns = [
    path("", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),
Run Code Online (Sandbox Code Playgroud)

我希望能够不显式设置 URL 字符串,而是在 HTTP 或 HTTPS 之间选择方案。有可能drf_yasg吗?

小智 8

在你的 Django settings.py 中添加这些

# Setup support for proxy headers
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您使用 nginx,请确保设置正确的标头 ( X-Forwarded-Proto )。实际上,检查最终用户和 Web 服务器(gunicorn / uwsgi)之间的所有 nginx 反向代理配置,例如主机上的 nginx 以及部署在 docker 中的 nginx。

location / {
    proxy_pass http://django:5000;
    proxy_set_header  Host              $http_host;
    proxy_set_header  X-Real-IP         $remote_addr;
    proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
    # check line below!
    proxy_set_header  X-Forwarded-Proto https;
    proxy_set_header  X-Forwarded-Referrer $http_referer;
    proxy_set_header  Referer $http_referer;
}
Run Code Online (Sandbox Code Playgroud)