Django

파이썬 장고 실무 심화 2주차 4_drf-yasg, 클래스형 view(cbv)

끈끈 2023. 4. 21. 02:25

 

drf-yasg

 

drf용 Swagger

 

pip install -U drf-yasg

 

 

drf_week2 > settings.py:

INSTALLED_APPS = [
    'django.contrib.staticfiles',  # required for serving swagger ui's css/js files
    'drf_yasg',
]

 

 

drf_week2 > urls.py:

from django.urls import path, include, re_path  # re_path 정규표현식 추가
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="Snippets API",
      default_version='v1',
      description="Test description",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@snippets.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=[permissions.AllowAny],
)

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'),
]

 

Swagger

 

https://drf-yasg.readthedocs.io/en/stable/readme.html

 

drf-yasg - Yet another Swagger generator — drf-yasg 1.20.1 documentation

Since the schema does not usually change during the lifetime of the django process, there is out of the box support for caching the schema view in-memory, with some sane defaults: caching is enabled by the cache_page decorator, using the default Django cac

drf-yasg.readthedocs.io

 


 

클래스형 view
(Class-based Views)

 

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)

    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_201_CREATED)
        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)

 

articles > urls.py:

urlpatterns = [
    path('', views.ArticleList.as_view(), name="index"),
    path('<int:article_id>/', views.ArticleDetail.as_view(), name="article_view"),
]

 

articles > views.py:

from drf_yasg.utils import swagger_auto_schema

    @swagger_auto_schema(request_body=ArticleSerializer)
    def post(self, request, format=None):

 

swagger

 

https://www.django-rest-framework.org/tutorial/3-class-based-views/

 

3 - Class based views - Django REST framework

We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code DRY. We'll start by rewriting the root view as a cla

www.django-rest-framework.org

 


 

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API

 

Fetch API - Web API | MDN

Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있습니다. XMLHttpRequest와 같은 비슷한 API가 존재합니다만, 새로운 Fetch API는 좀더 강력하고 유연한 조작이 가능합니

developer.mozilla.org

 

drf_week2_front > index.js:

window.onload = async function loadArticles() {
    const response = await fetch('http://127.0.0.1:8000/articles/', { method: 'GET' })

    response_json = await response.json()

    const articles = document.getElementById("articles")

    response_json.forEach(element => {
        const newArticle = document.createElement("div")
        newArticle.innerText = element.title
        articles.appendChild(newArticle)
    });
}

 


 

django-cors-headers

 

같은 domain

 

pip install django-cors-headers

 

 

drf_week2 > settings.py:

INSTALLED_APPS = [
    "corsheaders",
]


MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware", # 얘보다는 위에
]


CORS_ALLOW_ALL_ORIGINS = True

 

https://pypi.org/project/django-cors-headers/

 

django-cors-headers

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).

pypi.org