Wecode #11 TIL Django - Project 따라하기#3

황인용·2019년 12월 18일
0

wecode TIL

목록 보기
11/12

pango project에 comment기능 추가하기

기존 project에 comment기능을 추가
comment을 보내고, 보낸 comment을 받아 볼수 있는 API구축

1. python manage.py startapp comment

(pango)$ python manage.py startapp comment
(pango)$
(pango)$ tree
.
├── comment
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-37.pyc
│   │   ├── models.cpython-37.pyc
│   │   ├── urls.cpython-37.pyc
│   │   └── views.cpython-37.pyc
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── 0002_auto_20191216_1134.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       ├── 0001_initial.cpython-37.pyc
│   │       ├── 0002_auto_20191216_1134.cpython-37.pyc
│   │       └── __init__.cpython-37.pyc
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── pango
├── user
......
...
..
.

2. pango/setting.py 수정

  • INSTALLED_APPS
    'comment' 추가
ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
#    'django.contrib.admin',
#    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user',
    'comment',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
#    'django.middleware.csrf.CsrfViewMiddleware',
#    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

3. pango/urls.py 수정

  • urlpatterns
    comment path 추가
from django.urls import path, include

urlpatterns = [
    path('user', include('user.urls'))
    path('comment', include('comment.urls'))
    ]

4. comment/urls.py

  • comment 디렉토리 안에 urls.py 를 만들고 comment의 경로를 작성한다
(pango)$ vi comment/urls.py
from django.urls import path
from .views import CommentView

urlpatterns = [
        path('', CommentView.as_view())
]

5. comment/models.py

  • comment디렉토리에 models.py 만들고 database와 ORM할 class Users를 만듬
(pango)$ vi comment/models.py
from django.db import models

class Comments(models.Model):
    name = models.CharField(max_length=50)
    comment = models.CharField(max_length=300)

    class Meta:
        db_table = 'comments'

6. python manage.py makemigrations

(pango)$ python manage.py makemigrations comment

7. python manage.py migrate

(pango)$ python manage.py migrate comment

8. python shell

python shell모드에서 comment관련 database가 정상작동하는지, ORM이 잘 되는지 확인한다

(pango)$ pwd
/home/inyong/develop/pang
(pango)$ ls
comment  db.sqlite3  manage.py  pango  user
(pango)$ python manage.py shell
>>>

Database의 Data를 제데로 핸들링하는지 확인하기 위하여 Comments클래스를 import해야한다.

>>> from comment.models import Comments
>>>
>>> Comments.objects.all()
<QuerySet []>
>>> 
>>> Comments.objects.create(name='inyong', comment='안녕?')
<Comments: Comments object (3)>
>>>
>>> Comments.objects.all()
<QuerySet [<Comments: Comments object (3)>]>
>>>
>>> Comments.objects.all().values()
<QuerySet [{'id': 3, 'name': 'inyong', 'comment': '안녕?'}]>
>>> 

Comments.objects 는 Queryset 형태(객체들의 목록형태)로 저장된다.

9. comment/views.py

  • comment디렉토리에 views.py 만들고 CommentView클래스를 만든다
  • CommentView클래스는 post, get method를 포함
import json 

from django.views import View 
from django.http import JsonResponse
from .models import Comments

class CommentView(View):
    def post(self, request):
        data = json.loads(request.body)
        Comments(
            name = data['name'],
            comment = data['comment']
        ).save()

        return JsonResponse({'message':'comment Success!'}, status=200)

    def get(self, request):
        comment = list(Comments.objects.values())
        return JsonResponse({'data':comment}, status=200)

10. runserver & httpi 확인

[ 서버 ]

(pango)$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified some issues:

WARNINGS:
?: (urls.W002) Your URL pattern '/auth' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.

System check identified 1 issue (0 silenced).
December 18, 2019 - 11:33:04
Django version 3.0, using settings 'pango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

[ client ]

  • comment 등록 시 ( http => post )
(pango)$ http -v localhost:8000/comment name='pang', comment='이게 comment기능이다'
POST /comment HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 76
Content-Type: application/json
Host: localhost:8000
User-Agent: HTTPie/0.9.8

{
    "comment": "이게 comment기능이다",
    "name": "pang,"
}

HTTP/1.1 200 OK
Content-Length: 31
Content-Type: application/json
Date: Wed, 18 Dec 2019 11:34:37 GMT
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "message": "comment Success!"
}
  • comment 확인 ( http => get )
(pango)$ http -v localhost:8000/comment
GET /comment HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8000
User-Agent: HTTPie/0.9.8



HTTP/1.1 200 OK
Content-Length: 154
Content-Type: application/json
Date: Wed, 18 Dec 2019 11:35:35 GMT
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

{
    "data": [
        {
            "comment": "안녕?",
            "id": 3,
            "name": "inyong"
        },
        {
            "comment": "이게 comment기능이다",
            "id": 4,
            "name": "pang,"
        }
    ]
}
profile
dev_pang의 pang.log

0개의 댓글