장고 REST Framework 튜토리얼을 시도했습니다 (1) -Quickstart-

Amazon Linux release 2 (Karoo)

전제 조건
· Python3 설치
· Python3 가상 환경 생성 (python3 -m venv py37)
· Python3 가상 환경에 pip install로 Django와 Django REST Framework 설치
 → Django 2.2.1, Django REST Framework 3.9.3
· 사용자의 홈 디렉토리에 work라는 디렉토리가 작성되었습니다.

URL
장고 REST Framework -Quickstart-

장고 프로젝트 만들기
$ cd
$ cd work
$ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart
$ python manage.py migrate

# password:password123
$ python manage.py createsuperuser --email [email protected] --username admin

Serializers
$ cd quickstart
$ vi serializers.py

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

보기
$ vi views.py

tutorial/quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
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


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

URLs
$ cd ../tutorial
$ vi urls.py

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

Pagination, Settings
$ vi settings.py

tutorial/settings.py
INSTALLED_APPS = (
    ...
    'rest_framework',
)

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

Testing our API
$ cd ..
$ python manage.py runserver

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib64/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/management/base.py", line 390, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "/home/sano/py37/lib64/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/sano/py37/lib64/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module
    return import_module(self.urlconf_name)
  File "/usr/lib64/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/sano/work/tutorial/tutorial/urls.py", line 25, in <module>
    from tutorial.quickstart import views
ModuleNotFoundError: No module named 'tutorial.quickstart'


오류가 발생하여 움직이려고 시도했습니다.

'quickstart', '추가

tutorial/settings.py
INSTALLED_APPS = (
    ...
    'quickstart',
)

부분 수정

tutorial/urls.py
from django.contrib import admin
from django.conf.urls import url, include
from django.urls import include, path
#from rest_framework import routers
#from tutorial.quickstart import views
from quickstart.urls import router as quickstart_router

#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('admin/', admin.site.urls),
    path('', include(quickstart_router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
    #path('', include(router.urls)),
    #path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

파일 추가

quickstart/urls.py
from rest_framework import routers
from .views import UserViewSet, GroupViewSet

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

부분 수정

tutorial/quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
#from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
from .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

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

동작 확인
$ curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin",
            "email": "[email protected]",
            "groups": []
        }
    ]

브라우저를 시작하고 "htp://127.0.0.1:8000/우세 rs/"에 액세스

좋은 웹페이지 즐겨찾기