Pythonフレームワークdjangoの導入 


参考: 
[python3のインストール](https://qiita.com/MariMurotani/items/d5adc56a090e2f0e09dd)
[djangoのTutorial](https://docs.djangoproject.com/ja/1.11/intro/tutorial01/)
[スーパーユーザー作成](https://docs.djangoproject.com/ja/1.11/intro/tutorial02/)
[RESTAPI](https://qiita.com/kimihiro_n/items/86e0a9e619720e57ecd8)

[コード](https://github.com/MariMurotani/pytest)

環境: 
Darwin MariMurotaninoMacBookPro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 23 18:25:34 PDT 2016; root:xnu-3248.60.10~1/RELEASE_X86_64 x86_64
Python 3.6.3
Django 1.11.7
MySQL 5.6.36
# 1. djangoをインストール 
```
# install django
pip3 install django
# make sure installed packages
pip3 freeze

# make sure django version via console
python3

>Python 3.6.3 (default, Nov 14 2017, 10:10:22)
>[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
>Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
1.11.7
```

# 2. djangoプロジェクト作成
pytest projectを作成します。

```
$ python3 -m django --version
1.11.7

$ django-admin startproject pytest
```

# 3.サーバー起動 
```
$ python3 manage.py runserver
>Performing system checks...
>
>System check identified no issues (0 silenced).
>
>You have 13 unapplied migration(s). Your project may not work properly until >you apply the migrations for app(s): admin, auth, contenttypes, sessions.
>Run 'python manage.py migrate' to apply them.
>
>November 14, 2017 - 01:54:51
>Django version 1.11.7, using settings 'pytest.settings'
>Starting development server at http://127.0.0.1:8000/
>Quit the server with CONTROL-C.
```
![スクリーンショット 2017-11-14 10.55.48.png](https://qiita-image-store.s3.amazonaws.com/0/89997/3af57bcb-2b31-9ce2-8e55-175f3a699994.png)

マイグレーションしろって怒られてるので下記コマンドを実行します。
>Run 'python manage.py migrate' to apply them.

```
$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
```

# 4. sampleという名前のアプリを作成する
```
$ cd pytest
$ python3 manage.py startapp sample
```
<img width="218" alt="スクリーンショット 2017-11-14 11.04.21.png" src="https://qiita-image-store.s3.amazonaws.com/0/89997/5ef81a5a-e315-b4ee-e5c9-814a6a99e5bc.png">

## 1. ビューを追加

```python3:sample/views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("Hello, world. You're at the samples index.")
```

## 2. URLとビューの関連付け

```python3:sample/urls.py
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]
```

## 3. ルートのURLconfにURLを追加

```python3:pytest/urls.py
from django.conf.urls import include,url
from django.contrib import admin

urlpatterns = [
    url(r'^sample/', include('sample.urls')),
    url(r'^admin/', admin.site.urls),
]
```
![スクリーンショット 2017-11-14 11.26.30.png](https://qiita-image-store.s3.amazonaws.com/0/89997/588f24f4-fa09-57c7-2413-9c9b5fe8b118.png)

# 5. mysqlの設定
事前にpytestデータベースをローカルのMySQL内に作成しておきます。

```
$ pip3 install PyMySQL django
.....
>Successfully installed PyMySQL-0.7.11
```

```/pytest/settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'pytest',
        'USER': 'xxxxx',
        'PASSWORD': 'xxxx',
        'HOST': 'localhost',
        'PORT': '',
    }
}
```

```manage.py
import pymysql
pymysql.install_as_MySQLdb()
```

サーバー再起動でエラー

```
$ python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
```

**python manage.py migrate**を実行する

```
[ReDucate00047]$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
```
![スクリーンショット 2017-11-14 11.50.13.png](https://qiita-image-store.s3.amazonaws.com/0/89997/0f22e2e8-210f-79b6-644b-75a847c73f0d.png)

# 6. admin画面を使う
http://127.0.0.1:8000/admin/でアクセスできる事を確認
![スクリーンショット 2017-11-14 11.32.22.png](https://qiita-image-store.s3.amazonaws.com/0/89997/b3b8e303-17ad-2591-b6ba-fe6cf6a16ed5.png)

スーパーユーザーを作成してログインする

```
$ python3 manage.py createsuperuser
Username (leave blank to use 'hoge'): admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.

$ python3 manage.py runserver
```

#7. モデルの作成と管理画面への追加
モデルを追加

```python3:sample/models.py
class User(models.Model):
    name = models.CharField(max_length=32)
    mail = models.EmailField()
```

```python3:pytest/settings.py
INSTALLED_APPS = [
....
    'sample',
]
```
Migrationファイルの作成と実行

```
$ python3 manage.py makemigrations
$ python3 manage.py migrate
```

モデルを管理画面に追加

```sample/admin.py
from django.contrib import admin
from .models import User

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    pass
```
![スクリーンショット 2017-11-14 13.00.20.png](https://qiita-image-store.s3.amazonaws.com/0/89997/0537374f-b5c7-213e-df9a-c3d200253c3d.png)


# 8.RESTフレームワーク組み込み

```
# install API framework
pip3 install djangorestframework
pip3 install django-filter 
```

```python3:pytest/settings.py
INSTALLED_APPS = (
    ...
    'rest_framework',
)
```

シリアライザ作成

```python:sample/serializer.py
# coding: utf-8
from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('name', 'mail')
```

for APIの部分を先程作ったviewに追記します。

```python:sample/views.py
# for API
import django_filters
from rest_framework import viewsets, filters
from .models import User
from .serializer import UserSerializer


# Create your views here.
# API
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

```

```python:sample/urls.py
# coding: utf-8
# API
from rest_framework import routers
from .views import UserViewSet

# API
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
```

```python:pytest/urls.py
# API
from sample.urls import router as sample_router

urlpatterns = [
    url(r'^sample/', include('sample.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include(sample_router.urls)),
]
```

![スクリーンショット 2017-11-14 14.01.01.png](https://qiita-image-store.s3.amazonaws.com/0/89997/15e9e961-efbd-3e75-cd49-b48097c07959.png)

所要時間3-4時間ほどで取り急ぎシンプルなRESTAPI作成までこぎつけました!!