본문 바로가기
TIL

20210406 final project #2

by reo.l 2021. 4. 6.

지금까지 한 것

  • django rest framework tutorial
  • api 살펴보기

 

django 튜토리얼이 끝나고 drf에 대하여 공부했다. 이 부분은 아직 어려워서 따로 블로그에 정리하려 하고 먼저 Quickstart부분에 대하여 정리하려 한다.

 

# 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 ..

 

먼저 프로젝트 폴더를 생성하고 가상 환경을 설치하여 실행한다. django와 drf를 설치하여 주고 admin project를 만들어 준 뒤 project안에 app을 만들어 준다.

 

$ find .
.
./manage.py
./tutorial
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py

 

위의 구조로 프로젝트가 만들어진다.

 

python manage.py migrate

 

데이터베이스에 싱크 하여 주고

 

python manage.py createsuperuser --email admin@example.com --username admin

 

슈퍼 유저를 생성해 준다.

 

// tutorial/quickstart/serializers.py

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

 

app에 serializers를 만들어 주는데 이는 클라이언트에게 데이터를 보내줄 때 직렬화 하는 과정을 맡아 준다. 

 

// tutorial/quickstart/views.py

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

 

views로 가서 요청을 받았을 때 어떠한 데이터를 뿌려 줄지에 대한 부분을 작성한다. 현재는 viewSet을 통해 작성되어 있어 직관적으로 표현되지 않았지만 이 부분은 후에 정리를 할 예정이다. (viewSet은 crud부분을 명시하지 않아도 깔끔하게 해결해 준다.)

 

tutorial/urls.py

from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

 

이제 url을 매핑해 준다. 이 또한 굉장히 간단히 표현되어있는데 이 또한 viewSet을 이용하고 있기 때문에 routers 메서드를 사용하여 등록만 해주면 urlConf에서 자동으로 매핑해 준다. 이 부분 또한 후에 정리를 할 예정이다.

 

// tutorial/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

 

잊지 말아야 할 것은 drf를  사용할 때 settings파일에 명시해주어야 한다.

 

python manage.py runserver

bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

 

이제 서버를 실행하고 만들어놓은 슈퍼유저를 통해 요청을 보내면 정보를 가져올 수 있다. Quickstart부분에 굉장히 간단히 설명되어있지만 자세히 들어가면 많은 개념들이 들어가 있다. 후에 정리할 예정이다.

 

 

참고 : www.django-rest-framework.org/tutorial/quickstart/

 

 

 

'TIL' 카테고리의 다른 글

20210415 final project #4  (0) 2021.04.15
20210409 final project #3  (0) 2021.04.09
20210404 final project #1  (0) 2021.04.04
20210325 first project #5  (0) 2021.03.26
20210323 first project #4  (0) 2021.03.23

댓글