DjangoRestApi(DRF)の設定 その１

[こちら](https://hackernoon.com/creating-websites-using-react-and-django-rest-framework-b14c066087c7)を写経する(まだ途中)のと備忘録用

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

## 環境設定
お馴染みのvirtualenv

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

んでdjango projectを作成する

```bash
django-admin startproject backend
cd backend
django-admin startapp api
```
## DBの設定
何もしなければSQLiteになってる
このままでよければskipしてください。
自分はmysqlを使いたいので、mysqlの設定に変更する

setting.pyのDATABASESを下記にする

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

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

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

立ち上げて確認してみる

```bash
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](https://qiita-image-store.s3.amazonaws.com/0/199610/6372fd5b-7c8e-6d75-7116-9e44f3bd3424.png)

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

一度サーバー落とす

## DRFの設定
[公式サイト](http://www.django-rest-framework.org/#installation)を写経

markdownも入れる

```bash
pip3 install markdown
```
setting.pyのINSTALLED_APPSにrest_framework追加。
次いでREST_FRAMEWORKを丸々追加

```python
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も下記に変更する

```python3
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を作成

```python
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を書き換える

```python
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](https://qiita-image-store.s3.amazonaws.com/0/202660/8d90fa92-5216-f937-9fba-bed2c214bad2.png)
出来た!

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

```bash
curl -H 'Accept: application/json; indent=4' -u  username:password http://127.0.0.1:8000/users/
```
一旦ここまで