LoginSignup
2
2

More than 5 years have passed since last update.

Django REST Frameworkチュートリアルをやってみた(1) -Quickstart-

Last updated at Posted at 2019-05-05

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
・ユーザーのhomeディレクトリにworkというディレクトリ作成済

URL
Django REST Framework -Quickstart-

Djangoのプロジェクト作成

$ cd
$ cd work
$ django-admin startproject tutorial
$ cd tutorial
$ django-admin startapp quickstart
$ python manage.py migrate

# password:password123
$ python manage.py createsuperuser --email admin@example.com --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')

Views

$ 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": "admin@example.com",
            "groups": []
        }
    ]

ブラウザを起動して「 http://127.0.0.1:8000/users/ 」にアクセス
確認.PNG

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2