您可以覆盖 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")),