Django REST framework ๊ณต์๋ฌธ์์ ์ผ๋ถ ๊ธ๋ค์ ๋ณด๊ณ ์ ๋ฆฌํ ๋ด์ฉ์ด๋ค.
front-end์ back-end์ ์์
ํจ์จ์ฑ์ ๋์ด๊ธฐ ์ํด์๋ ๊ฐ๋ฐ์์ญ์ ์์ ํ ๊ตฌ๋ณ๋๋ ๊ฒ์ด ์ด์์ ์ด๋ฉฐ, ๊ทธ๋ฌ๊ธฐ ์ํด์๋ REST API ๊ฐ ํ์ํ๋ฉฐ, ์ฌํ์ฉ์ฑ๋ ๋์์ง๋ค.
์ฌ๊ธฐ์๋ ๊ณต์๋ฌธ์ tutorial์ ๋ณด๊ณ ๋ฐ๋ผํด๋ณด์์ผ๋ฉฐ, ์์ธํ ์ค๋ช
์ ๋ค์ ๋์จ๋ค.
settings
Copy $ pip install djangorestframework
Copy # settings.py
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
]
์ค์น๊ฐ ์๋ฃ๋๋ฉด INSTALLED_APPS
์ ์ถ๊ฐํด์ค๋ค.
ํ๋ก์ ํธ ์์ํ๊ธฐ
Copy $ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart
$ ./manage.py migrate
$ ./manage.py createsuperuser --email admin@example.com --username admin
Serializers tutorial/quickstart
ํ์์ serializers.py
ํ์ผ์ ๋ง๋ค์ด์ค๋ค.
Copy from django . contrib . auth . models import User , Group
from rest_framework import serializers
class UserSerializer ( serializers . HyperlinkedModelSerializer ):
class Meta :
model = User
fields = [ 'url' , 'username' , 'email' , 'groups' ]
class GroupSerializer ( serializers . HyperlinkedModelSerializer ):
class Meta :
model = Group
fields = [ 'url' , 'name' ]
Views tutorial/quickstart/views.py
ํ์ผ์ ์ด์ด ๋ค์๊ณผ ๊ฐ์ด ์์ ํ๋ค.
Copy from django . contrib . auth . models import User , Group
from rest_framework import viewsets
from quickstart . serializers import UserSerializer , GroupSerializer
class UserViewSet ( viewsets . ModelViewSet ):
queryset = User . objects . all (). order_by ( '-date_joined' )
serializer_class = UserSerializer
class GroupViewSet ( viewsets . ModelViewSet ):
queryset = Group . objects . all ()
serializer_class = GroupSerializer
URLs
Copy from django . contrib import admin
from django . urls import path , include
from rest_framework import routers
from quickstart import views
router = routers . DefaultRouter ()
router . register ( r 'users' , views.UserViewSet)
router . register ( r 'groups' , views.GroupViewSet)
urlpatterns = [
path ( '' , include (router.urls)),
path ( 'api-auth/' , include ( 'rest_framework.urls' ,namespace = 'rest_framework' ))
]
๊ฐ ํ์ด์ง๋ง๋ค ๋ช๊ฐ์ ๊ฒ์๊ธ์ ๋
ธ์ถํ ์ง ์ง์ ํ ์ ์๋ค.
Copy # tutorial/settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS' : 'rest_framework.pagination.PageNumberPagination' ,
'PAGE_SIZE' : 15
}
tutorial/settings.py
ํ๋จ์ ์์ ๊ฐ์ด ์ฝ๋๋ฅผ ์ถ๊ฐํด์ค๋ค.
Copy $ ./manage.py runserver
์ ํํ http://localhost:8000
์ผ๋ก ๋ค์ด๊ฐ๋ณด๋ฉด ํ์ธํ ์ ์๋ค.