Django: Westagram Code Review

Seoyul Kim·2020년 4월 11일
0

Project

목록 보기
2/2
#test01/urls.py

from django.urls import path, include

urlpatterns = [
    path('account', include('account.urls')),
    path('comment', include('comment.urls')),
]
#account/urls.py

~
from django.urls import path

from .views import SignUpView, SignInView

urlpatterns = [
    path('/signup', SignUpView.as_view()),
    path('/signin', SignInView.as_view()),
]
  • path의 URL 끝에 /(슬래쉬)를 치면 그 다음이 있다는 것을 의미하므로 'signup/'이 아닌 '/signup'으로 적어준다
#comment/urls.py

from django.urls import path

from .views import CommentView

urlpatterns = [
    path('', CommentView.as_view())
]
#account/models.py

from django.db import models

class Account(models.Model):
    username = models.CharField(max_length = 50)
    password = models.CharField(max_length = 400)

    class Meta:
        db_table = 'accounts'
  • Meta 옵션은 inner class로 사용하여 상위 클래스에게 meta data를 제공하며 다양한 옵션들이 있다. db_table을 사용하여 데이터베이스 테이블명을 설정해준다.
#account/views.py

import json

from django.views import View
from django.http import HttpResponse, JsonResponse

from .models import Account

class SignUpView(View):
    def post(self, request):
        data = json.loads(request.body)
        try:
            if Account.objects.filter(username=data['username']).exists():
                return JsonResponse({'message':'USERNAME_EXIST'}, status=401)
            else: Account.objects.create(       #1)
                username = data['username'],
                password = data['password']
            )
            return HttpResponse(status=200)
        except KeyError:
                return JsonResponse({'message':'INVALID_KEY'}, status=400)
        

class SignInView(View):
    def post(self, request):
        data = json.loads(request.body)
        try:
            user = Account.objects.filter(username = data['username'])   #2)
            if user.exists():
                acc = Account.objects.get(username = data['username'])    #3)
                if acc.password == data['password']:      #4)
                    return HttpResponse(status=200)
                return JsonResponse({'message':'PASSWORD_WRONG'}, status=401)     #5)
            return JsonResponse({'message':'INVALID_USER'}, status=401)      #6)
        except KeyError:
            return JsonResponse({'message':'INVALID_KEY'}, status=400)
~
  • class 이름은 다양한 메소드를 사용할 수 있게 설정한다.(ex)POST method만 사용할 것 같은 이름은 사용하지 않는다.)
  • 1) else를 사용하지 않고, indent를 조절한다.
  • 2), 3) 특별히 재사용 하지 않을 시 변수에 따로 담지 않고 바로 사용한다.
  • 4) 변수명은 줄임말을 사용하지 않는다.
  • 5), 6) 에러 메세지를 너무 자세하게 적어주지 않고 에러 코드만 적어준다.
#comment/models.py

from django.db import models
from account.models import Account

class Comment(models.Model):
        username = models.ForeignKey(Account, on_delete=models.CASCADE)
        comment = models.TextField(max_length = 400)
        updated_at = models.DateTimeField(auto_now = True)
        created_at = models.DateTimeField(auto_now_add = True)

        class Meta:
                db_table = 'comment'
#comment/views.py

import json

from django.views import View
from django.http import HttpResponse, JsonResponse

from .models import Comment
from account.models import Account

class CommentView(View):
    def post(self, request):
        data = json.loads(request.body)
        try:
            if Account.objects.filter(username = data['username']).exists():
                Comment.objects.create(
                    username = Account.objects.get(username=data['username']),  
                    comment = data['comment']
                )
                return HttpResponse(status=200)
            return JsonResponse({'message':'INVALID_USER'}, status=401)
        except KeyError:
            return JsonResponse({'message':'INVALID_KEY'},status=400)

    def get(self, request):
        data = json.loads(request.body)     #1)
        comment_data = Comment.objects.filter(username = Account.objects.get(username=data['username']))
        return JsonResponse({'comments':list(comment_data.values())}, status=200)
  • 1) get은 바디로부터 데이터를 입력받지 않으므로 삭제해야 한다.

0개의 댓글