我正在使用 drf_yasg 制作 swagger 文档。当我在 AWS Application Load Balancer 后面发布我的 DRF 应用程序并将监听器设置为监听 443 HTTPS 并重定向到运行 DRF 的我的 EC2 时,swagger UI 正在尝试将请求发送到端点 http://example.com/status 而不是例如https://example.com/status。这会产生 Google Chrome 错误:
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.
所以我解决这个问题的方法是在 drf_yasg.views.get_schema_view 中明确设置我的服务器 URL。所以我的代码看起来像:
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"),
我希望能够不显式设置 URL 字符串,而是在 HTTP 或 HTTPS 之间选择方案。 在 drf_yasg 中是否可行?
请您参考如下方法:
将这些添加到您的 Django settings.py 中
# Setup support for proxy headers
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
