如何在Django中打开swagger地址
时间: 2024-05-12 22:15:26 浏览: 203
要在Django中打开Swagger地址,需要遵循以下步骤:
1. 首先,确保您已经安装了drf_yasg库。
2. 在您的Django项目的settings.py文件中,添加以下行:
```python
INSTALLED_APPS = [
# ...
'drf_yasg',
]
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False,
'SECURITY_DEFINITIONS': {
'Token': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
},
}
```
3. 在您的Django项目的urls.py文件中,添加以下行:
```python
from django.conf.urls import url
from django.urls import path, include
from rest_framework import routers
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
from drf_yasg.views import get_schema_view as yasg_schema_view
from drf_yasg import openapi
schema_view = yasg_schema_view(
openapi.Info(
title="API Documentation",
default_version='v1',
description="API documentation",
terms_of_service="#",
contact=openapi.Contact(email="#"),
license=openapi.License(name="MIT License"),
),
validators=['ssv', 'flex'],
public=True,
permission_classes=(),
)
urlpatterns = [
# ...
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
```
4. 在您的Django项目中运行服务器,并访问 http://localhost:8000/swagger/,即可打开Swagger UI界面。
希望这能帮助到你!
阅读全文