LoginSignup
14
25

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-11-14

参考:
python3のインストール
djangoのTutorial
スーパーユーザー作成
RESTAPI

コード

環境:
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

マイグレーションしろって怒られてるので下記コマンドを実行します。

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

スクリーンショット 2017-11-14 11.04.21.png

1. ビューを追加

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とビューの関連付け

sample/urls.py
from django.conf.urls import url

from . import views

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

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

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

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

6. admin画面を使う

http://127.0.0.1:8000/admin/でアクセスできる事を確認
スクリーンショット 2017-11-14 11.32.22.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. モデルの作成と管理画面への追加

モデルを追加

sample/models.py
class User(models.Model):
    name = models.CharField(max_length=32)
    mail = models.EmailField()
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

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

# install API framework
pip3 install djangorestframework
pip3 install django-filter 
pytest/settings.py
INSTALLED_APPS = (
    ...
    'rest_framework',
)

シリアライザ作成

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に追記します。

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

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

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

14
25
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
14
25