2

我正在使用 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 检测到,我可以对这个端点做些什么?

4

1 回答 1

0

您可以覆盖 oauth2_provider 的默认 TokenView 类,如下所示:

视图.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")),
于 2017-11-21T03:03:25.930 回答