기본 콘텐츠로 건너뛰기

django REST API practice like a boss

pycharm 안녕.
django project 생성.

실행환경은 virtualenv로 3.6.x
virtualenv 생성에 약간 시간 소모.
setting.py와 urls.py가 반겨줌

djex1 프로젝트를 만들었음
__init__.py
settings.py
urls.py
wsgi.py
요렇게 생김.

자, 게임을 시작해볼까?
option+R 누름.

이런 애가 나옴.
startapp product 라고 쳐서 product 업무를 만들어보자.
자동완성이 된다.

product 아래
admin.py
apps.py
models.py
tests.py
views.py
이런 파일들이 생겼다. rails 생각이 난다.
내용물은 텅텅 비어서 실망스럽다.
comment라도 있을 줄 알았는데.
여튼 텍스트로 hello world 같은 건 안찍어본다. 바로 rest API
http://www.django-rest-framework.org/tutorial/quickstart/
돌입한다.
pip install djangorestframework
뭔가 설치했으니
requirements.txt로 pip freeze하여 깡통인 곳에서 설치할때 pip install -r requirements.txt로 설치할 수 있게 만들자.
pip freeze > requirements.txt

REST API framework는 설치했고 DB를 만들자.
먼저 migrate을 돌려주자.
option+R 상태에서 migrate 엔터
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 auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK
Following files were affected
 /Users/spectrum/Documents/python/djex1/db.sqlite3
이런 식으로 죽 올라가고 db.sqlite3 이란 파일이 생겼다.
로컬디비가 기본이 sqlite다.
pycharm의 툴을 이용해서 연결해놓자.
아니 이렇게 좋은 것이?
만일 처음 sqlite data source를 추가하는 것이면 Download missing driver files 라고 나올 수도 있는데 Download를 누르면 알아서 드라이버를 받는다.
기본은 pycharm 에서 관리하는 경로인데 File: 에서 ... 을 눌러 현재 프로젝트의 db.sqlite3랑 연결하자.
Project에서 Copy Path 해놓은 걸 붙여넣기 하면 편하다.
Test Connection 눌러서 Successful 떨어지는 거 구경하고 OK
기본 서비스가 훌륭
DB가 있으니 모델을 만들자.
product/models.py 에 자동완성을 써가면서 만들어 보았다.
from django.db import models

class Product(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.TextField()
    price = models.IntegerField()
    createdAt = models.DateTimeField(auto_now_add=True)
오케이 makemigrations product 해보자
App 'product' could not be found. Is it in INSTALLED_APPS?
하고 묻는다.
djex1/settings.py 에 INSTALLED_APPS를 수정하자.
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # apps
    'product',
]
시키는 대로 했다.
Migrations for 'product':
  product/migrations/0001_initial.py
    - Create model Product

Following files were affected 
 /Users/spectrum/Documents/python/djex1/product/migrations/0001_initial.py
migrations 파일이 생겼다.
Database는 변함이 없는데
방금 생성한 migrations 를 가지고 실제 table들을 만들자
option+R 상태에서 migrate
그리고 python console 에서 확인해보자.
PyDev console: starting.
Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Django 2.0.1
>>> from product.models import Product
>>> Product.objects.all()
<QuerySet []>
좋아보인다. import를 하는 순간. Product가 watch에 보이는게 좋다.

db 를 새로고침하면
테이블명이 엄하다.
업무명인 product에 entity명도 product 니 product_product로 나올 수 밖에.
graphviz로 ERD도 뽑아보자.
brew install graphviz
pip install django-extensions
pip install pygraphviz
쭉 설치하고
djex1/settings.py 에 INSTALLED_APPS에 django-extensions 추가
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'product',
    # extension
    'django_extensions',]
option+R에서 graph_models product -o test.png 뽑아본다.

괜찮네.
어드민도 있었지. 한번 볼까.
option+R에서 createsuperuser
유저명/이메일/암호 다 넣고
녹색 삼각형 눌러서 django Rrrrrrrrrrrun!
createsuperuser로 진입하면 이렇게 된다.
groups/users가 기본이고 users에 admin계정 하나 달랑 들었다.

view 만들어 볼 차례다.

product/views.py 를 열고
from rest_framework.generics import ListAPIView
from rest_framework import serializers
from product.models import Product
3개를 import 하자. ListAPIView하고 serializers는 이 view에서 사용할 것이고 대상인 모델은 product.models의 Product이다.
실제로 화면에 연결할 View를 만들기 전에 Product model을 가져와보자.
그냥은 가져올 수 없고 serializers.ModelSerializer 를 사용하는 serializer를 먼저 만들어야한다.
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
이정도면 일단 오케이
여기에 실제 url 과 연결할 View를 만들자
class ProductsView(ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
중요한 건 queryset.
product/views.py는 이렇게 완성하자.
from rest_framework.generics import ListAPIView
from rest_framework import serializers
from product.models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product

class ProductsView(ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
나머지는 연결하는 것만 남았다.
djex1/urls.py 의 최종모습은
from django.contrib import admin
from django.urls import include, path
from product.views import ProductsView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('product/', ProductsView.as_view()),
]
이와 같다.
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
커멘트에 있는 내용대로 path와 View 클래스.as_view()로 연결했다.

API서버가 완성되었다.
http://127.0.0.1:13000/product/?format=json 하면 [] 값만 나오기도 한다.

django admin을 이용해 model로 만든 테이블에 값을 입력해보자.
product/admin.py 에서 admin.site.register() 를 사용하여 model을 추가한다.
model은 from product.models import Product 있으니
from django.contrib import admin
from product.models import Product
admin.site.register(Product)
이정도면 된다.
/admin 을 보자.

Product / Products가 나왔다.
+ Add 를 눌러서 데이터를 입력할 수 있다.

relation을 만들기 위해 Coupon도 한번 만들어보자.
class Coupon(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    product_id = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
    )
    createdAt = models.DateTimeField(auto_now_add=True)
product_id라는 필드를 foreignkey로 product와 완결했다.
product삭제시에 같이 삭제되도록 models.CASCADE를 지정했다.
product/admin.py를 조금 손봐서
from django.contrib import admin
from product.models import Product, Coupon

class ProductAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'price')

class CouponAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'product_id')

admin.site.register(Product, ProductAdmin)
admin.site.register(Coupon, CouponAdmin)
이렇게 만들고 django admin에서 값을 입력해보면
이 경우 Coupon -> Product 인 상태에서 
1. Coupon을 기준으로 Product 접근:
  Coupon.objects.get(id=2).product_id.price # 한개
  Coupon.objects.filter(id=2).select_related() # 일치하는 여러개
2. Product를 기준으로 Coupon 접근:
  Product.objects.get(id=2).coupon_set.all() # 한개
  Product.objects.filter(id=2).prefetch_related() # 일치하는 여러개
이 가능하다.

이번에 처음 django를 써봤는데 안정적이고 완성도 높은 framework이네.
admin하나만 해도 꽤 훌륭해보인다.

댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.org 를