728x90
반응형
참고자료
https://www.django-rest-framework.org/tutorial/3-class-based-views/
FBV > CBV로 바꾸기
## articles/views.py
...
from rest_framework.views import APIView
class ArticleList(APIView):
def get(self, request, format=None):
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, format=None):
serializer = ArticleSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ArticleDetail(APIView):
def get(self, request, article_id, format=None):
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article)
return Response(serializer.data)
def put(self, request, article_id, format=None):
article = get_object_or_404(Article, id=article_id)
serializer = ArticleSerializer(article, data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, article_id, format=None):
article = get_object_or_404(Article, id=article_id)
article.delete()
return Response("삭제 완료", status=status.HTTP_204_NO_CONTENT)
기존에 있던 articleAPI, articleDetailAPI는 삭제하자
## articles/urls.py
urlpatterns = [
path('', views.ArticleList.as_view(), name='index'),
path('<int:article_id>/', views.ArticleDetail.as_view(), name='article_view'),
]
CBV에서 Swagger post 사용하기
## article/views.py
...
from drf_yasg.utils import swagger_auto_schema
class ArticleList(APIView):
def get(self, request, format=None):
articles = Article.objects.all()
serializer = ArticleSerializer(articles, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
@swagger_auto_schema(request_body=ArticleSerializer)
def post(self, request, format=None):
serializer = ArticleSerializer(data = request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Uploaded by N2T
728x90
반응형