from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.inspectors import NotHandled
from django.contrib import admin
from django.urls import path, include, re_path
class MySchemaGenerator(OpenAPISchemaGenerator):
def get_schema(self, request=None, public=False):
schema = super().get_schema(request, public)
# 删除 PATCH 请求
for path in schema['paths']:
if 'patch' in schema['paths'][path]:
schema['paths'][path].pop('patch')
return schema
def get_path_items(self, path, method, view):
"""
Get a list of (view_method, view_instance) pairs corresponding to the given path and http method.
Returns an empty list if there is no match.
"""
items = super().get_path_items(path, method, view)
if method.lower() == 'put' or method.lower() == 'delete':
# 如果请求方法是 PUT 或 DELETE,则添加对应的视图方法到列表中
try:
items.append((getattr(view, method.lower()), view))
except AttributeError:
raise NotHandled("HTTP method '%s' not supported by this view" % method)
return items
schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
description="help tesp api 辅助文档",
default_version='v1',
),
public=True,
permission_classes=[permissions.AllowAny],
generator_class=MySchemaGenerator,
)
urlpatterns = [
re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
path('admin/', admin.site.urls),
]