首页 > 解决方案 > 设置中的 Django FORCE_SCRIPT_NAME

问题描述

我正在努力寻找以下代码的作用的信息:

if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )

什么是线程本地 URL 解析器脚本?是否设置了这些脚本的前缀?它有什么意义,和配置网络服务器和环境变量有关系吗?

from django.utils.version import get_version

VERSION = (3, 0, 1, 'alpha', 1)

__version__ = get_version(VERSION)


[docs]def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS)

标签: django

解决方案


文档没有说太多,但说:

这将用作任何 HTTP 请求中的 SCRIPT_NAME 环境变量的值

我的理解是它是一个变量,可以包含某些脚本使用的脚本根的全局路径。如果需要,可以在 settings.py 中设置。

就我而言,我收到了来自 Swagger (drf_yasg) 的警告消息:

path component of api base URL https://example.com/ is ignored; use FORCE_SCRIPT_NAME instead

为了解决这个小问题,我做了以下设置:

urls.py(api):

schema_view = get_schema_view(
openapi.Info(
  title="Super API",
  default_version='v1',
  description="",
  terms_of_service="https://example.com/terms-of-service/",
  contact=openapi.Contact(email="dev@example.com"),
  license=openapi.License(name="BSD License"),
  ),
  url='https://example.com',   # <========
  public=True,
  permission_classes=(permissions.AllowAny,),
  )

设置.py

FORCE_SCRIPT_NAME = '/'

这导致不再有此警告,并且 Swagger 显示正确的基本 URL。

在此处输入图像描述

希望这会有所帮助。


推荐阅读