3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DjangoRestApi(DRF)の設定 その1

Last updated at Posted at 2018-01-07

こちらを写経する(まだ途中)のと備忘録用

フロントエンドReact, バックエンドDRFの環境設定に興味ある人は
読む価値あり

環境設定

お馴染みのvirtualenv

virtualenv env
source env/bin/activate # mac. windowsは env\Scripts\activate.bat
pip3 install django djangorestframework django-filter
pip3 freeze > requirements.txt

んでdjango projectを作成する

django-admin startproject backend
cd backend
django-admin startapp api

DBの設定

何もしなければSQLiteになってる
このままでよければskipしてください。
自分はmysqlを使いたいので、mysqlの設定に変更する

setting.pyのDATABASESを下記にする

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbname',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': 'hostname',
        'PORT': '3306',
    }
}

pysqlclientが入ってないとエラーになるのでinstallする

pip3 install mysqlclient
# 次にMigrateする
python manage.py makemigrations
python manage.py migrate

立ち上げて確認してみる

python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
January 05, 2018 - 11:49:15
Django version 2.0.1, using settings 'backend.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

ブラウザで*127.0.0.1:8000/*を見てみると
Screenshot-2018-1-5 Django the Web framework for perfectionists with deadlines .png

画面がカッコよくなってる!

一度サーバー落とす

DRFの設定

公式サイトを写経

markdownも入れる

pip3 install markdown

setting.pyのINSTALLED_APPSにrest_framework追加。
次いでREST_FRAMEWORKを丸々追加

INSTALLED_APPS = (
    ...
    'rest_framework',
)

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

urls.pyも下記に変更する

from django.conf.urls import url, include
from rest_framework import routers
from api import views
from django.contrib import admin

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 = [
    url(r'^', include(router.urls)),
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

backend/api/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')

またbackend/api/views.pyを書き換える

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from api.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

サーバー走らせてみて見ると
Screenshot-2018-1-7 Api Root – Django REST framework.png
出来た!

curlからも通っているのが分かる

curl -H 'Accept: application/json; indent=4' -u  username:password http://127.0.0.1:8000/users/

一旦ここまで

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?