You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在drf-spectacular中仅保留Redoc URL并解决路由报错

解决方法

报错的核心原因是:Redoc UI 默认依赖名为schema的路由来获取 OpenAPI 规范的 JSON 数据,你删除了SpectacularAPIView(name=schema)的路由后,Redoc 找不到数据源,就会抛出反向解析失败的错误。

要仅保留 Redoc 路由并解决报错,有两种可行方案:

方案一:保留SpectacularAPIView但隐藏/限制访问

保留生成 schema 的核心视图,但调整路由路径或添加访问限制,避免用户直接访问,同时让 Redoc 能正常获取数据:

from django.urls import path
from drf_spectacular.views import SpectacularAPIView, RedocView
# 若要限制访问,可导入Django的权限装饰器
# from django.contrib.auth.decorators import login_required

urlpatterns = [
    # 保留schema视图,修改为非公开路径(比如加internal前缀)
    # 若需限制内部访问,可添加装饰器:path('api/schema/internal/', login_required(SpectacularAPIView.as_view()), name='schema'),
    path('api/schema/internal/', SpectacularAPIView.as_view(), name='schema'),
    # 仅保留Redoc路由,它会自动通过name='schema'反向解析获取数据
    path('api/schema/redoc/', RedocView.as_view(), name='redoc'),
]

这样用户只能访问api/schema/redoc/,而 schema 的路径因不公开,普通用户无法直接访问。

方案二:修改Redoc的schema_url参数,不依赖反向解析

直接给 RedocView 指定 schema 的访问路径,无需保留schema这个路由名称:

from django.urls import path
from drf_spectacular.views import SpectacularAPIView, RedocView

urlpatterns = [
    # 保留schema视图,但不需要指定name
    path('api/schema/raw/', SpectacularAPIView.as_view()),
    # 配置Redoc时,直接通过schema_url指定schema的路径
    path('api/schema/redoc/', RedocView.as_view(schema_url='/api/schema/raw/'), name='redoc'),
]

这种方式更灵活,你可以随意设置 schema 的路径,只要 Redoc 能通过指定的 URL 拿到 JSON 数据即可。

额外检查

如果项目中其他代码(比如自定义视图、序列化器)也用到了reverse('schema'),需要同步修改这些代码,替换为新的路由名称或直接写死路径,避免其他地方也出现同样的反向解析错误。

内容的提问来源于stack exchange,提问作者Setare Kalantari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:05:43