Django REST Framework(DRF)
1. 가상환경 셋팅 및 프로젝트 설정
pip install djangorestframework
→ DRF 설치
# Create the project directory
mkdir tutorial
cd tutorial
# Create a virtual environment to isolate our package dependencies locally
python3 -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
# Install Django and Django REST framework into the virtual environment
pip install django
pip install djangorestframework
# Set up a new project with a single application
django-admin startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin startapp quickstart
cd ..
● 프로젝트 setting.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
INSTALLED_APPS += [
'rest_framework',
]
2. Serializer
- Queryset, Model 과 같은 복잡한 데이터를 JSON, XML 형태로 변환시켜줌
- Restful API는 JSON형태로 데이터를 보내야 하기 때문에 HTTP 랜더링을 사용하는 Django Template를 사용하지 못하고 Serializer를 사용하여 JSON형태로 변환시켜 보냄
- ModelForm과 유사하게 동작
● serializers.py
from rest_framework import serializers
from .models import Notice
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
class NoticeSerializer(serializers.ModelSerializer):
class Meta:
model = Notice
fields = ('name', 'title', 'content',)
3. View
● views.py
from django.contrib.auth.models import User
from .models import Notice
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, NoticeSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
class NoticeViewSet(viewsets.ModelViewSet):
queryset = Notice.objects.all()
serializer_class = NoticeSerializer
permission_classes = [permissions.IsAuthenticated]
4. URL
● urls.py
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from tutorial.quickstart import views
notice_list = NoticeView.as_view({
'post': 'create',
'get': 'list'
})
notice_detail = NoticeView.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
urlpatterns = format_suffix_patterns([
path('auth/', include('rest_framework.urls', namespace='rest_framework')),
path('notice/', notice_list, name='notice_list'),
path('notice/<int:pk>/', notice_detail, name='notice_detail'),
])