Westagram_3

Jina·2020년 4월 13일
0

Django

목록 보기
7/11

code review

Westagram_1에 있는 코드 리뷰한 내용을 적어둠
아래의 내용은 수정된 내용

test1.urls.py

from django.urls import path, include

urlpatterns = [
      path('account', include('account.urls')),
     path('comments',include('comments.urls')),
 ]

test1/urls.py에서 path 지정할 때 앱 이름만 쓰고 뒤에 / 쓰지 않기
restAPI 규칙상 URL의 뒷쪽에 / 를 해주지 않음

app뒤에 아무것도 안담길 가능성이 있기 때문에 경로 설정할 때 뒤에다 / 쓰는 것보다 앞에다 / 쓰는것이 권장됨

따라서 이 경우는 / 써주지 않고 app 경로 지정에 / 붙여주기

account app

account/models.py

 from django.db import models

 class Account(models.Model):
     name = models.CharField(max_length=200)
     email = models.CharField(max_length=200)
     password = models.CharField(max_length=400)
     created_date = models.DateTimeField(auto_now_add=True)
     updated_date = models.DateTimeField(auto_now=True)

     class Meta:
         db_table = "accounts"

class명 만들 때 동사로 짓는 것 보다는 명사느낌으로
하나의 동작을 크게 의미하는 class명을 짓는 것은 추천하지 않음
재사용성이 가능하며 명확한 의미를 담는 것이 좋음

예시) Signup 보다는 User 등으로

account/views.py

import json
from django.views import View
from django.http import JsonResponse, HttpResponse
from .models import Account

class AccountView(View):
     def post(self,request):
         data = json.loads(request.body)
         if Account.objects.filter(email=data['email']).exists():
             return HttpResponse(status=400)
             
         Account.objects.create(
             name     = data['name'],
             email    = data['email'],
             password = data['password']
            )
        return HttpResponse(status=200 )


 class LoginView(View):
     def post(self,request):
         data = json.loads(request.body)
         try:
           password = data['password']
           if Account.objects.filter(email=data['email']).exists():
               if Account.objects.get(email=data['email']).password == password:
                  return HttpResponse(status=200)
               return HttpResponse(status=401)
           return HttpResponse(status=401)
         except KeyError:
           return JsonResponse({"message":"INVALID_USER"}, status=400)

1) Response
JsonResponse 까지 return하면 친절해보이지만 보안상에서는 추천하지 않음
HttpResponse로 해주는 것이 더 좋음

2) try, except
이 곳에서의 try, except는 비밀번호나 이메일 등 입력해야하는 내용들을 다 입력하지 않은 경우에 나오는 내용

account/urls.py

 from django.urls import path
 from .views import AccountView, LoginView

 urlpatterns = [
     path('/sign_up',AccountView.as_view()),
     path('/sign_in',LoginView.as_view())
 ]

app의 url경로 앞부분에 / 입력해주기

comments app

comments/models.py

 from django.db import models

 class Comment(models.Model):
     email = models.CharField(max_length=200)
     reply = models.TextField()
     crated_reply = models.DateTimeField(auto_now_add=True)
     updated_reply = models.DateTimeField(auto_now=True)

     class Meta:
         db_table = "comments"

comments/views.py

from django.views import View
from django.http import JsonResponse,HttpResponse
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(email=data['email']).exists():
                Comment(
                     email = Account.objects.get(email=data['email']),
                     reply = data['reply']
                ).save()
                return HttpResponse(status=200)

            return JsonResponse({"message":"INVALID_USER"}, status=401)
        except KeyError:
            return JsonResponse({"message":"INVALID_KEYS"}, status=400)

class MyReplyView(View):
    def get(self,request,address):
        my_reply= Comment.objects.filter(email=address).values('reply')
        return JsonResponse({"comment":list(my_reply)},status=200)

1) foreignkey
나의 경우는 account와 comments를 foreignkey로 연결하지 않았으나 연결해주는 것이 좋음

foreignkey로 연결되어 있을 때 아래와 같이 사용할 수 있음
email = Account.objects.get(email=data['email'])

위와 같은 방법은 진짜 데이터에서 객체를 연결해주는 느낌
원래 내가 사용했던 방식은 데이터의 string만 가져오는 느낌

2) 변수
변수를 재사용할 예정이 없으면 웬만하면 변수를 지정해주지 않는 것이 좋음

3) for문
굳이 for문 써주지않아도 쿼리셋의 특징을 이용하면 데이터를 가져올 수 있음

comments/urls.py

 from django.urls import path
 from .views import CommentView, MyReplyView

 urlpatterns = [
     path('',CommentView.as_view()),
     path('/<str:address>',MyReplyView.as_view()),
 ]

comment 자체가 그냥 reply의미여서 굳이 또 한번 경로를 지정해 줄 필요는 없음

0개의 댓글