DRF(Django Rest Framework) venv 가상환경 설치 후 진행(Django - 가상환경 만들기)
name | version |
---|---|
django | 5.0.3 |
djangorestframework | 3.14.0 |
Django 와 DRF 설치
% pip install django djangorestframework
Successfully installed asgiref-3.7.2 django-5.0.3 djangorestframework-3.14.0 pytz-2024.1 sqlparse-0.4.4
Django 프로젝트 설치 && member app 설치
% django-admin startproject myproject
% cd myproject
% python manage.py startapp member
myproject/settings.py rest_framework,member 추가
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'member'
]
model.py
from django.db import models
# Create your models here.
class Member(models.Model):
name = models.CharField(max_length=30)
description = models.TextField()
created = models.DateTimeField(auto_now_add=True)
serializer.py 직렬화 ( json 또는 그 반대로 변환해준다)
from .models import Member
from rest_framework import serializers
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = '__all__'
api view
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404
from .models import Member
from .serializer import MemberSerializer
# Create your views here.
class MemberList(APIView):
def get(self, request):
members = Member.objects.all()
# 여러 개의 객체를 serialization하기 위해 many=True로 설정
serializer = MemberSerializer(members, many=True)
return Response(serializer.data)
def post(self, request):
serializer = MemberSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class MemberDetail(APIView):
def get_object(self, pk):
try:
return Member.objects.get(pk=pk)
except Member.DoseNotExist:
raise Http404
def get(self, _, pk):
member = self.get_object(pk)
serializer = MemberSerializer(member)
return Response(serializer.data)
def put(self, request, pk):
member = self.get_object(pk)
serializer = MemberSerializer(member, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, _, pk):
member = self.get_object(pk)
member.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
api view 2
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, generics
from django.http import Http404
from .models import Member
from .serializer import MemberSerializer
# Create your views here.
class MemberList(generics.GenericAPIView):
serializer_class = MemberSerializer
queryset = Member.objects.all()
def get(self, request):
members = self.queryset
# 여러 개의 객체를 serialization하기 위해 many=True로 설정
serializer = self.serializer_class(members, many=True)
return Response({
"status": "success",
"data": serializer.data
})
def post(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"status": "success", "data": serializer.data}, status=status.HTTP_201_CREATED)
return Response({"status": "fail", "message": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
class MemberDetail(generics.GenericAPIView):
serializer_class = MemberSerializer
def get_object(self, pk):
try:
return Member.objects.get(pk=pk)
except Member.DoseNotExist:
raise Http404
def get(self, _, pk):
member = self.get_object(pk)
serializer = self.serializer_class(member)
return Response(serializer.data)
# HTTP Method -> PUT:자원 전체 수정 PATCH:자원 일부 수정
def put(self, request, pk):
member = self.get_object(pk)
serializer = self.serializer_class(member, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, _, pk):
member = self.get_object(pk)
member.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
member/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
path('member/', views.MemberList.as_view()),
path('member/<int:pk>', views.MemberDetail.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns)
project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('testapp.urls')),
path('', include('member.urls'))
]
mig
% python manage.py makemigrations
% python manage.py migrate
% python manage.py runserver
open api 설치
pip install drf_yasg