+ API schema as Redoc

+ Django & DRF API exceptions in one format
This commit is contained in:
Phil Zhitnikov 2024-05-21 01:19:10 +04:00
parent fa5e1cd860
commit 16db83fd6d
5 changed files with 32 additions and 1 deletions

View File

@ -1,3 +1,4 @@
from .celery import app as celery_app
import poizonstore.schema
__all__ = ('celery_app',)

18
poizonstore/exceptions.py Normal file
View File

@ -0,0 +1,18 @@
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError as DRFValidationError
from rest_framework.views import exception_handler as drf_exception_handler
def exception_handler(exc, context):
""" Handle Django ValidationError as an accepted exception """
if isinstance(exc, DjangoValidationError):
if hasattr(exc, 'message_dict'):
exc = DRFValidationError(detail={'error': exc.message_dict})
elif hasattr(exc, 'message'):
exc = DRFValidationError(detail={'error': exc.message})
elif hasattr(exc, 'messages'):
exc = DRFValidationError(detail={'error': exc.messages})
return drf_exception_handler(exc, context)

View File

@ -98,6 +98,7 @@ INSTALLED_APPS = [
'debug_toolbar',
'django_filters',
'mptt',
'drf_spectacular',
'account',
'store',
@ -185,7 +186,10 @@ REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.TokenAuthentication'],
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_PAGINATION_CLASS': 'utils.drf.StandardResultsSetPagination'
'DEFAULT_PAGINATION_CLASS': 'utils.drf.StandardResultsSetPagination',
'EXCEPTION_HANDLER': 'poizonstore.exceptions.exception_handler',
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
DJOSER = {

View File

@ -18,6 +18,7 @@ from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView
urlpatterns = [
@ -28,3 +29,9 @@ urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL)
# API schema
if settings.DEBUG:
urlpatterns += [
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]

View File

@ -24,6 +24,7 @@ tqdm==4.65.0
django-debug-toolbar==4.1.0
requests==2.31.0
python-dotenv==1.0.1
drf-spectacular==0.27.2
# Logging
sentry-sdk==1.34.0