我正在使用django-rest-swagger 2.1.1版。 我使用oauth2_provider.urls来构建oauth2 / token端点,如下所示:
urlpatterns = [
url(r'^oauth2/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
问题是Swagger没有将其检测为端点,因此我的openapi.json文件中缺少它。
我可以对此端点做些什么才能被Swagger检测到?
答案 0 :(得分:0)
您可以覆盖oauth2_provider的默认TokenView类,如下所示:
views.py:
class TokenAPIView(TokenView, APIView):
schema = ManualSchema(fields=[
coreapi.Field(
"client_id",
required=True,
location="query",
schema=coreschema.String()
),
coreapi.Field(
"client_secret",
required=True,
location="query",
schema=coreschema.String()
),
coreapi.Field(
"grant_type",
required=True,
location="query",
schema=coreschema.String()
),
])
permission_classes = (AllowAny,)
server_class = oauth2_settings.OAUTH2_SERVER_CLASS
validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS
def post(self, request, *args, **kwargs):
"""
Create an oauth2 token
"""
return super().post(request, *args, **kwargs)
并且还替换默认的get_schema_view:
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView
from rest_framework_swagger import renderers
class SwaggerSchemaView(APIView):
permission_classes = [IsAuthenticated]
exclude_from_schema = True
renderer_classes = [
renderers.OpenAPIRenderer,
renderers.SwaggerUIRenderer
]
def get(self, request):
generator = SchemaGenerator(title='API Endpoints')
schema = generator.get_schema()
return Response(schema)
urls.py:
oauth2_endpoint_views = [
url(r'^token/$', TokenAPIView.as_view(), name="token"),
]
url(r'^$', SwaggerSchemaView.as_view()),
url(r'^oauth/', include(oauth2_endpoint_views, namespace="oauth2_provider")),