drf-spectacular未生成django-oauth-toolkit的OpenAPI Schema URL问题
解决oauth2_provider URL未纳入OpenAPI Schema的问题
1. 完善SPECTACULAR_SETTINGS配置
在settings.py的SPECTACULAR_SETTINGS中添加OAuth2相关配置,让spectacular识别并生成对应Schema:
SPECTACULAR_SETTINGS = { # 保留原有配置,新增以下内容 'OAUTH2_FLOWS': ['password', 'authorization_code'], 'OAUTH2_AUTHORIZATION_URL': '/oauth/authorize/', 'OAUTH2_TOKEN_URL': '/oauth/token/', 'OAUTH2_REFRESH_URL': '/oauth/token/', 'OAUTH2_SCOPES': { 'read': '读取权限', 'write': '写入权限', # 根据你的实际权限范围调整 }, # 确保不排除oauth相关路径 'EXCLUDE_PATHS': [], }
2. 手动为TokenView添加Schema注释
如果自动识别失效,直接在urls.py中给TokenApiView扩展Schema定义:
from drf_spectacular.utils import extend_schema from oauth2_provider.views import TokenView # 为TokenView的POST方法添加Schema描述 @extend_schema( request={ 'application/x-www-form-urlencoded': { 'type': 'object', 'properties': { 'grant_type': {'type': 'string', 'enum': ['password', 'refresh_token']}, 'username': {'type': 'string'}, 'password': {'type': 'string'}, 'refresh_token': {'type': 'string'}, 'client_id': {'type': 'string'}, 'client_secret': {'type': 'string'}, }, 'required': ['grant_type'] } }, responses={200: { 'type': 'object', 'properties': { 'access_token': {'type': 'string'}, 'token_type': {'type': 'string'}, 'expires_in': {'type': 'integer'}, 'refresh_token': {'type': 'string'}, 'scope': {'type': 'string'}, } }} ) class ExtendedTokenView(TokenView): pass # 在urlpatterns中替换原TokenView urlpatterns = [ # 其他路由... path('oauth/token/', ExtendedTokenView.as_view(), name='token'), path('schema/', SpectacularAPIView.as_view(), name='schema'), ]
3. 确保spectacular扫描到目标URL
- 确认oauth2的路由在项目主
urlpatterns中,或被include的子路由未被spectacular排除 - 运行生成命令时,指定完整的urlconf(如果主路由不在默认位置):
python manage.py spectacular --file schema.yaml --urlconf your_project.urls
4. 安装OAuth2扩展依赖
确保安装了spectacular的OAuth2支持包:
pip install drf-spectacular[oauth2]
内容的提问来源于stack exchange,提问作者Alberto Sanmartin Martinez
相关产品推荐
相关产品推荐

