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'),
]
https://drf-yasg.readthedocs.io/en/stable/readme.html
클래스형 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):
https://www.django-rest-framework.org/tutorial/3-class-based-views/
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API
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' 카테고리의 다른 글
Token 인증_JWT(JSON Web Token) (0) | 2023.04.21 |
---|---|
파이썬 장고 실무 심화 3주차_JWT 토큰 로컬스토리지 (2) | 2023.04.21 |
포스트맨(Postman) 사용법 (2) | 2023.04.19 |
파이썬 장고 실무 심화 2주차 3_PUT, DELETE (0) | 2023.04.19 |
파이썬 장고 실무 심화 2주차 2_serializer, GET, POST (3) | 2023.04.19 |