Django + djangorestframework + django_rest_swagger 시작

테스트환경

CentOS release 6.8 (Final)

Python 3.4.6

Django-1.10.5

djangorestframework-3.5.3

django_rest_swagger-2.1.1

MariaDB-server-10.0.29

pipenv-3.2.11

 

1. CentOS release 6.8 (Final)

    1-1. centos 6.8 minimal 설치

    1-2. Development tools 설치

    ]# yum update

    ]# yum groupinstall 'Development tools'

 

2. Python 3.4.6

    2-1. Python 3.4.6 설치

    ]# wget https://www.python.org/ftp/python/3.4.6/Python-3.4.6.tgz

    ]# tar zxf Python-3.4.6.tgz

    ]# cd Python-3.4.6

    ]# ./configure --prefix=/usr/local/python3.4 --enable-shared

    ]# make

    ]# make install

    ]# echo "/usr/local/python3.4/lib" >> /etc/ld.so.conf.d/python3.4.conf

    ]# ldconfig

    ]# /usr/local/python3.4/bin/pip3 install pipenv

    ]# ln -s /usr/local/python3.4/bin/python3 /usr/local/bin/

    ]# ln -s /usr/local/python3.4/bin/python3.4 /usr/local/bin/

    ]# ln -s /usr/local/python3.4/bin/pip3 /usr/local/bin/

    ]# ln -s /usr/local/python3.4/bin/pip3.4 /usr/local/bin/

    ]# ln -s /usr/local/python3.4/bin/pipenv /usr/local/bin/

    ]# ln -s /usr/local/python3.4/bin/virtualenv /usr/local/bin/

    

    Tip: https://www.python.org/dev/peps/pep-0513/#ucs-2-vs-ucs-4-builds

          --enable-unicode=ucs4 옵션은 CPython 2.x, 3.0 ~ 3.2 까지만 사용한다.

 

3. MariaDB-server-10.0.29

    3-1. MariaDB-server-10.0.29 설치

    ]# vi /etc/yum.repos.d/MariaDB.repo

    [mariadb]

    name = MariaDB

    baseurl = http://yum.mariadb.org/10.0/centos6-amd64

    gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB

    gpgcheck=1

    

    ]# yum install MariaDB-server MariaDB-client MariaDB-devel

    ]# /etc/rc.d/init.d/mysqld start

    ]# mysql -u root

    MariaDB [(none)]> CREATE DATABASE test_django CHARACTER SET UTF8;

    MariaDB [(none)]> CREATE USER django@localhost IDENTIFIED BY '비밀번호';

    MariaDB [(none)]> CREATE USER django@127.0.0.1 IDENTIFIED BY '비밀번호';

    MariaDB [(none)]> GRANT ALL PRIVILEGES ON test_django.* TO django@localhost;

    MariaDB [(none)]> GRANT ALL PRIVILEGES ON test_django.* TO django@127.0.0.1;

    MariaDB [(none)]> FLUSH PRIVILEGES;

 

4. Django-1.10.5, djangorestframework-3.5.3, django_rest_swagger-2.1.1, mysqlclient-1.3.9

    4-1. Django, djangorestframework, django_rest_swagger, mysqlclient 설치

    ]# mkdir /home/test-django

    ]# cd /home/test-django

    ]# pipenv install mysqlclient django djangorestframework django-rest-swagger

    

5. djangorestframework tutorial 시작

]# pipenv shell

(test-django) ]# django-admin startproject test_api

(test-django) ]# cd test_api

(test-django) ]# vi test_api/settings.py

 

"""

ALLOWED_HOST 수정

DATABASE 수정

"""

- ALLOWED_HOSTS = []

+ ALLOWED_HOSTS = ['*']

 

- DATABASES = {

-    'default': {

-        'ENGINE': 'django.db.backends.sqlite3',

-        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

-    }

- }

 

+ DATABASES = {

+    'default': {

+        'ENGINE': 'django.db.backends.mysql',

+        'NAME': 'test_django',

+        'USER': 'django',

+        'PASSWORD': '비밀번호',

+        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on

+        'PORT': '3306',

+        'OPTIONS': {

+            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

+        },

+    }

 

}

 

 

""" migrate 수행 """

(test-django) ]# ./manage.py migrate

 

""" admin 계정 생성 """

(test-django) ]# ./manage.py createsuperuse

 

""" app 추가 """

(test-django) ]# ./manage.py startapp v1

 

""" Post 모델 작성 """

(test-django) ]# vi v1/models.py

from django.db import models

class Post(models.Model):
   title = models.CharField(max_length=200)
   content = models.TextField()
   created_at = models.DateTimeField(auto_now_add=True)
   updated_at = models.DateTimeField(auto_now=True)

   def __str__(self):
       return "{}: {}".format(self.pk, self.title)

 

""" INSTALLED_APPS 에 v1, rest_framework, rest_framework_swagger 추가 """

(test-django) ]# vi test_api/settings.py

INSTALLED_APPS.append('v1')
INSTALLED_APPS.append('rest_framework')
INSTALLED_APPS.append('rest_framework_swagger')

 

""" v1 App의 Post 모델 생성 """

(test-django) ]# ./manage.py makemigrations v1

(test-django) ]# ./manage.py migrate v1

 

 

""" admin 페이지에서 Post 관리할 수 있도록 추가 """

(test-django) ]# vi v1/admin.py

from django.contrib import admin
from .models import *

admin.site.register(Post)

 

""" serializers 클래스 생성 """

(test-django) ]# vi v1/serializers.py

from rest_framework import serializers
from .models import *

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

 

""" viewset 클래스 생성 """

(test-django) ]# vi v1/views.py

 

from django.shortcuts import render from .models import * from .serializers import * from rest_framework import viewsets class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer

 

 

 

""" app urls 생성 및 project urls 에 추가 """

(test-django) ]# vi v1/urls.py

 

from django.conf.urls import include, url from .views import * from rest_framework import routers from rest_framework_swagger.views import get_swagger_view router = routers.DefaultRouter() router.register(r'post', <PostViewSet) schema_view = get_swagger_view(title='TEST API') urlpatterns = [ url(r'^', include(router.urls)),

url(r'^swagger', schema_view) , ]

 

from django.conf.urls import include, url

from .views import *

from rest_framework import routers

from rest_framework_swagger.views import get_swagger_view

 

router = routers.DefaultRouter()

router.register(r'post', PostViewSet)

 

schema_view = get_swagger_view(title='TEST API')

 

urlpatterns = [

    url(r'^', include(router.urls)),

    url(r'^swagger', schema_view),

 

]

 

 

(test-django) ]# vi test_api/urls.py

"""test_api URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [url(r'^admin/', admin.site.urls),url(r'^v1/', include('v1.urls')),]

 

from django.conf.urls import include, url

from django.contrib import admin

 

urlpatterns = [

    url(r'^admin/', admin.site.urls),

    url(r'^v1/', include('v1.urls')),

 

]

 

 

""" 실행 """

(test-django) ]# ./manage.py runserver 0.0.0.0:80

 

""" 웹브라우져로 접속 및 테스트 """

 

 

 

 

 

기본적인 예제를 테스트 해보았고 공식 tutorial 사이트를 방문해서 단계별로 테스트를 진행해야한다...

http://www.django-rest-framework.org/#tutorial



출처: http://pyman.tistory.com/50 []

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
252 파이썬-sql알케미-tutorial, sqlalchemy tutorial file 졸리운_곰 2018.08.27 185
251 Data Structures and Algorithm In python 파이썬으로 자료구조와 알고리즘 : 출처 인터넷 file 졸리운_곰 2018.08.27 315
250 Mastering Basic Algorithms in the Python Language 이북 출처 인터넷 file 졸리운_곰 2018.08.27 381
249 텐서플로우-#1 자료형의 이해 file 졸리운_곰 2018.08.15 272
248 How to build a simple neural network in 9 lines of Python code file 졸리운_곰 2018.08.14 294
247 node.js python-shell을 활용하여 python 실행 file 졸리운_곰 2018.08.14 365
246 Python, PyV8로 javascript 실행하기 file 졸리운_곰 2018.08.14 221
245 파이썬 플라스크 프레임워크 소개 졸리운_곰 2018.08.03 130
244 주피터(jupyter notebook) 원격 접속 file 졸리운_곰 2018.07.10 142
243 Pycharm 원격 서버 연결하기 file 졸리운_곰 2018.07.10 249
242 The Ultimate Flask Front-End – Part 2 file 졸리운_곰 2018.06.22 85
241 The Ultimate Flask Front-End file 졸리운_곰 2018.06.22 139
» Django + djangorestframework + django_rest_swagger 시작 file 졸리운_곰 2018.05.27 65
239 Does Python SciPy need BLAS? 졸리운_곰 2018.05.26 85
238 PyCharm과 함께 DJango와 RestFramework를 활용한 웹 사이트 구축하기 file 졸리운_곰 2018.05.22 192
237 Flask-RESTPlus에서 REST API와 Swagger 문서를 통합 file 졸리운_곰 2018.05.22 353
236 Building beautiful REST APIs using Flask, Swagger UI and Flask-RESTPlus file 졸리운_곰 2018.05.22 263
235 [Python] Flask & flask-restplus && swagger ui file 졸리운_곰 2018.05.22 147
234 Django에서 MySQL DB를 연동하기 pycharm file 졸리운_곰 2018.04.10 427
233 Python Flask 로 간단한 REST API 작성하기 file 졸리운_곰 2018.04.07 226
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED